SQL Server 2008 database copy - file permissions - sql-server

For SQL Server 2008 Developer Edition on Vista 64 bit:
I tried copying a database using a Vista admin account using the attach/detach method and it failed due to a file permission error so I gave the user that sql services are running as write and modify to the directory. The copy didn't work. I then gave it full control. The copy worked.
Does that make sense?
If I revoke full control from the user, will that cause problems?
The weird thing is that in an existing working database with files in a different directory, there are no special permissions on the directory and files for the database, so why does a copy require full control?

When you detach a DB, the MDF/LDF files may be set with more restricted perms than you expect, like exclusive to the principal that did the detach - maybe the SQL Server service account or the domain account of the user that performed the detach. I have in the past had to manually add back permissions on the files' Properties > Security tab for other users, or else the files act as if they are locked. See also http://www.onupdatecascade.com/2009/07/sql-server-locks-mdf-and-ldf-files-upon.html
also: http://msdn.microsoft.com/en-us/library/ms189128.aspx
( thanks GrumpyOldDBA )

If the server and/or data you are working on does not require those restrictive permissions to be set, you can set a startup flag in SQL Server that will override this function. I understand what Microsoft is going for with this - they assume if you detach a DB they don't want just anyone to walk away with the file; however, I think keeping a good hacker from doing that is easier said than done, and encrypting the DB is the best method for safeguarding data.
Anyway, there is a "Trace Flag 1802" which is oddly named, since it's nothing to do with tracing. You'll want to add it to your SQL startup in SQL Configuration Manager if you want to keep this behavior.
https://support.microsoft.com/en-us/kb/922804
I myself had the same issue and found the answer in StackExchange:
https://dba.stackexchange.com/a/77683/11001

Related

Restore SQL Server database from bak file to different partition (Permission Denied)

On Ubuntu 17.04, I have a .bak file in /var/opt/mssql/backup/ that I am trying to restore to a separate partition because the partition I have SQL Server installed on does not have enough room for the database to be restored to.
I am getting an error like the following: The operating system returned the error '5(Access is denied.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on '/media/<my-user-name>/<some-folder>/<mdf-file>.mdf'.
I've tried to use chmod and chown to change the permissions of that folder on the second partition, but I'm not getting it quite right because I still get the error.
What user is trying to write to that folder in the second partition?
How do I get that user account permissions to successfully restore the database to that folder?
I had this second hard drive connected via a caddy and was able to perform this task no problem. But as soon as I installed the ssd internally, Ubuntu has not allowed whatever user account I'm using in the SQL Server CLI for it this time.
Thanks!
Update
I changed the owner of the second partition/ssd to mssql and now I have permission to restore the database to this location. I would assume that if the owner of that whole ssd is mssql, I might have other permission issues down the road using this ssd for other things. Is there a way to configure this so that my personal user account as well as mssql has permissions to this folder enough to own it? I don't think two different accounts can own a folder, but is there a way to permit multiple accounts with sufficient access to perform these actions?
I won't pretend to be knowledgeable about this, but I had a permissions issue while trying to restore a .bak that was on a network vm to my local device, it worked when I added it to a .zip with 7-share, then copied it to the location I wanted and extracted it.
I had the permissions issue when I tried to move it without zipping, and as far as I remember I still had this issue when I used send to compressed (zipped) folder. I'm not sure why, maybe someone else can elaborate
I solve the problem by deleting the old database, creating a new one and restoring the backup to the new one.
My problem was probably cause by the fact that I had created the database in evalutation edition of MS SQL Server and I wanted to rewrite it by backup in new instalation of developer edition.

TSQL and UNC Paths

I'm not an expert with TSQL so have patience with me please. So recently I was doing a project in TSQL on my local server using SQL Server 2008 R2 Management Studio. I was reading my files from a temp file on my C: drive and bulk inserting them into tables at the time.
Then I went and moved to a regular server instead of my local server on my machine.
It took me a bit to realize that I no longer had access to my local machine folders and files, and that is causing me issues.
I've read that one solution is to create a mapped drive on the server, but this is not an option for me.
So my question is what are other options for me? Could I use UNC paths to access my files or anything else?
The files I want to access are regular text files that are comma-delimited and newline terminated.
(I saw somewhat similar questions to mine, but there's seemed server specific or specific to their particular issues. Also none of their questions were answered.)
Actually a mapped drive won't work either because the account SQL runs under by default (local system if I recall) will not have network access.
So, the more reliable way to do this is definitely with a UNC path BUT there is more! (I've done this several times when I've needed to move database backups and log backups across servers for mirroring).
How?
On the SQL server machine AND the other server that will host the share, create a new user (same username and password on both machines) - assuming your not using AD. The user needs not be in any groups at all other than the users group but it must be called the same in both servers and the password must match.
On the SQL server machine change the account that SQL SERVER is running under. This is done in the SQL server configuration tool. Do not try to do this yourself via windows services. Choose the user that you created in no 1 above. Note you have to enter the pw. Restart SQL after you've changed it and verify SQL still runs fine. It should run just as before but now is running as a particular user with all the permissions of that user (which actually are very limited anyhow, but at least the user can access network resources).
On the remote server, make sure the new user has NTFS permissions on the folders that will host your share. Read/write perhaps or just read if SQL is only reading data.
On the remote server, create a share pointing to the appropriate folder that you set permissions for above. Make sure if you're using share permissions that the new user also has permissions on the share (not just on NTFS on the drive).
Once all of this is setup, your SQL scripts simply use the UNC path that points to the remote share and since SQL is running "as" a user with access to that share, SQL will see the files just fine!

Cannot bulk load. Operating system error code 5 (Access is denied.)

For some weird reason I'm having problems executing a bulk insert.
BULK INSERT customer_stg
FROM 'C:\Users\Michael\workspace\pydb\data\andrew.out.txt'
WITH
(
FIRSTROW=0,
FIELDTERMINATOR='\t',
ROWTERMINATOR='\n'
)
I'm confident after reading this that I've setup my user role correctly, as it states...
Members of the bulkadmin fixed server role can run the BULK INSERT statement.
I have set the Login Properties for the Windows Authentication correctly (as seen below).. to grant server-wide permissions on bulkadmin
(source: iforce.co.nz)
And the command EXEC sp_helpsrvrolemember 'bulkadmin' tells me that the information above was successful, and the current user Michael-PC\Michael has bulkadmin permissions.
(source: iforce.co.nz)
But even though I've set everything up correctly as far as I know, I'm still getting the error. executing the bulk insert directly from SQL Server Management Studio.
Msg 4861, Level 16, State 1, Line 2
Cannot bulk load because the file "C:\Users\Michael\workspace\pydb\data\andrew.out.txt" could not be opened. Operating system error code 5(Access is denied.).
which doesn't make sense because apparently bulkadmins can run the statement, am I meant to reconfigure how the bulkadmin works? (I'm so lost). Any ideas on how to fix it?
This error appears when you are using SQL Server Authentication and SQL Server is not allowed to access the bulk load folder.
So giving SQL server access to the folder will solve the issue.
Here is how to:
Go to the folder right click ->properties->Security tab->Edit->Add(on the new window) ->Advanced -> Find Now. Under the users list in the search results, find something like SQLServerMSSQLUser$UserName$SQLExpress and click ok, to all the dialogs opened.
I don't think reinstalling SQL Server is going to fix this, it's just going to kill some time.
Confirm that your user account has read privileges to the folder in question.
Use a tool like Process Monitor to see what user is actually trying to access the file.
My guess is that it is not Michael-PC\Michael that is trying to access the file, but rather the SQL Server service account. If this is the case, then you have at least three options (but probably others):
a. Set the SQL Server service to run as you.
b. Grant the SQL Server service account explicit access to that folder.
c. Put the files somewhere more logical where SQL Server has access, or can be made to have access (e.g. C:\bulk\).
I suggest these things assuming that this is a contained, local workstation. There are definitely more serious security concerns around local filesystem access from SQL Server when we're talking about a production machine, of course this can still be largely mitigated by using c. above - and only giving the service account access to the folders you want it to be able to touch.
I had the same problem SSIS 2012 and the solution was to use Windows Authentication. I was using SQL authentication with the sa user.
Go to start run=>services.msc=>SQL SERVER(MSSQLSERVER) stop the service
Right click on SQL SERVER(MSSQLSERVER)=> properties=>LogOn Tab=>Local System Account=>OK
Restart the SQL server Management Studio.
Try giving the folder(s) containing the CSV and Format File read permissions for ‘MSSQLSERVER’ user (or whatever user the SQL Server service is set to Log On As in Windows Services)
This is what worked for me:
Log on SSIS with Windows authentication.
1. Open services and find MSSQL NT Service account name and copy it:
2. Open folder from which SQL server should read from. Security - Group or user names tab - Add and paste there copied account:**
You will probably get "Multiple names found error", just select MSSQL user:
Your BULK INSERT query should run fine now.
If problem persists try adding SQL Server Agent account to folder permissions in same way.
Make sure you restart MSSQL server in services after you are done.
This is quite simple the way I resolved this problem:
open SQL Server
right click on database (you want to be backup)
select properties
select permissions
select your database role (local or cloud)
in the you bottom you will see explicit permissions table
find " backup database " permission and click Grant permission .
your problem is resolved .
sometimes this can be a bogus error message, tried opening the file with the same account that it is running the process. I had the same issue in my environment and when I did open the file (with the same credentials running the process), it said that it must be associated with a known program, after I did that I was able to open it and run the process without any errors.
Make sure the file you're using ('C:\Users\Michael\workspace\pydb\data\andrew.out.txt') is on the SQL server machine and not the client machine running MSSMS.
1) Open SQL
2) In Task Manager, you can check which account is running the SQL - it is probably not Michael-PC\Michael as Jan wrote.
The account that runs SQL need access to the shared folder.
I have come to similar question when I execute the bulk insert in SSMS it's working but it failed and returned with "Operation system failure code 5" when converting the task into SQL Server Agent.
After browsing lots of solutions posted previously, this way solved my problem by granting the NT SERVER/SQLSERVERAGENT with the 'full control" access right to the source folder.
Hope it would bring some light to these people who are still struggling with the error message.
In our case it ended up being a Kerberos issue. I followed the steps in this article to resolve the issue: https://techcommunity.microsoft.com/t5/SQL-Server-Support/Bulk-Insert-and-Kerberos/ba-p/317304.
It came down to configuring delegation on the machine account of the SQL Server where the BULK INSERT statement is running. The machine account needs to be able to delegate via the "cifs" service to the file server where the files are located. If you are using constrained delegation make sure to specify "Use any authenication protocol".
If DFS is involved you can execute the following Powershell command to get the name of the file server:
Get-DfsnFolderTarget -Path "\\dfsnamespace\share"

"Cannot open user default database. Login failed." after installing SQL Server Management Studio Express

I have a database in a local file that is used by a program. The program has limited functionality and I needed to run some quick queries. I installed SQL Server Management Studio Express 2005 (SSMSE), connected to the SQL Server instance, attached the database file, and ran the queries. Now the original program will no longer connect to the database. I receive the error:
Cannot open user default database. Login failed. Login failed for user 'MyComputer\MyUserName'.
I've gone back into SSMSE and tried to set the default database. I've opened up Security, Logins, BUILTIN\Administrators and BUILTIN\Users. Under General, I have set the default database to the program's database. Under User Mappings, I made sure the database is ticked and that db_datareader and db_datawriter are ticked.
The program uses the connection string:
Server=(local)\Instance; AttachDbFilename=C:\PathToDatabase\Database.mdf; Integrated Security=True; User Instance=True;
I know jack-all about database administration. What else am I missing?
This may not be answering your question specifically, but it may help others with similar issue caused by different problem
In my case the problem was my user is defaulted to a database which is not accessible for any reason (can be renamed, removed, corrupted or ...)
To solve the issue just follow the following instruction
Try to login again on the login page there is other tabs select
"Connection Properties".
under the tab locate "Connect to database" and select an existing database you have access to like tempdb or master
Once you are connected to the SQL Server Instance execute the below TSQL to assign the login a new default database.
Use master
GO
ALTER LOGIN [yourloginname] WITH DEFAULT_DATABASE = TempDB
GO
Alternatively once you connected change your default database name to master via UI
Article taken from :
http://www.mytechmantra.com/LearnSQLServer/Fix-cannot-open-user-default-database-Login-failed-Login-failed-for-user-SQL-Server-Error/
This problem manifested for me when I took my default db offline. Next thing I know I couldn't login. Switching to the Connection Properties tab and selecting the drop down to change the database I want to connect to also failed.
It let me in right away once I manually typed master as the db I wanted to connect to (on the Connection Properties tab).
First, try to isolate your problem:
Take a backup of the file! Some of the steps below can, apparently, in some circumstances cause the file to vanish.
Are you sure you are connecting to the same instance through Management Studio as the program is?
If possible, try to shut down the instance that you are not expecting to use.
Set the user's default database to master and try to make the program logon.
Try to login as the user through Management Studio - since you have integrated security, you should open Management Studio as the program's user.
Are you using "User instances" - perhaps without knowing it? If so, this may be helpful: http://blogs.msdn.com/b/sqlexpress/archive/2006/11/22/connecting-to-sql-express-user-instances-in-management-studio.aspx
I haven't worked much with files being attached in the way your program does - but you write that you attached the DB in the Management Studio as well. Have you tried detaching it there before running your program? Perhaps you are seeing the Management Studio and your program competing for exclusive access to the MDF-file?
EDIT: I added point 6 above - this is new in my own list of TODOs when troubleshooting this type of Login failed. But it does sound a lot like what you're experiencing.
EDIT2: In the first edit, new item was added to the list. So the numbers in the comments doesn't correspond with the numbers in the answer.
I finally figured this out, and my situation is different than every other I've read about tonight.
I had restored my database from a backup. I knew that there was a particular login user that I had been using, so I created that user in SSMS. However, there was already a user by that name under the database that had come in with the backup.
Since I had screwed around so much trying to fix this, I wasn't able to delete the user under the DB easily. I deleted the database and restored again. Then:
Delete the user under the Databases->[my database]->Users
Create the user again in Security->Logins (not under your DB, although that probably works too.
Go to the newly created user. Select properties. Then under User Mappings, tell it to make your database the default. Give it read and write access.
Summary: I had two users. One that came with the DB, and one that I had created. Remove the one that came with the DB and create your own.
First click on Option>> Button of “Connect to Server” Prompt.
Now change the connect to database to any existing database on your server like master or msdb.
More Details
https://blog.sqlauthority.com/2008/11/04/sql-server-fix-error-4064-cannot-open-user-default-database-login-failed-login-failed-for-user/
I've also had this same problem, it turned out that I was trying to access the built in membership classes (in a view), and that .Net was trying to create the database in the App_Data folder:
#Membership.GetUser().ProviderUserKey
This will trigger the system to try and create a database based in the built in membership system, which may not be the way your system is setup.
I had a similar problem had to simply download SQL Express Utility that is capable of starting User Instances. SSEUtil is a tool written by the Visual Studio team to help troubleshoot User Instance issues, you can read more about it in the read me file that is installed with the utility.
http://www.microsoft.com/downloads/details.aspx?FamilyID=fa87e828-173f-472e-a85c-27ed01cf6b02&DisplayLang=en.
Hope this will help.
In my case I had to set "connect to any database" right path:
On your instance, go to Security , then to Logins.
Right Click on there, you will see properties and you should click on Securables.
There it give possibility to connect to any database.

SQL Server Copy Database Issue

I'm running the copy database wizard on a 2008 R2 instance of SQL Server.
The database I want to copy is a SQL 2000 database.
I'm copy that database to another SQL SErver 2008 R2.
The wizard uses SQL authentication for both servers, and both are sysadmins.
When I run it, I get the following error (FYI I have tried both copying the logins and leaving them out):
Event Name: OnError
Message: ERROR : errorCode=-1073548784 description=Executing the query "sys.sp_addrolemember #rolename = N'RandomRoleName..." failed with the following error: "The role 'RandomRoleName' does not exist in the current database.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
helpFile= helpContext=0 idofInterfaceWithError={C81DFC5A-3B22-4DA3-BD3B-10BF861A7F9C}
StackTrace: at Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer()
at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.TransferDatabasesUsingSMOTransfer()
Any help would be appreciated!
Jim
My suggestion is dont use the copy database wizard. Create a full backup of the database on the 2000 server and then restore it on the 2008 server.
If you google "Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer Copy Database Wizard" you will find that many many people have gotten this same error or other nearly identical smo errors... no-one appears to have gotten past it.
That's isn't to say its impossible... just, restoring a backup is so much easier then the wizard or troubleshooting the wizard. Good luck.
The copy wizard had missed some security and IIRC it's caused by subtle differences in security tables, principals etc between the 2 versions.
Frankly, the easiest way is to do one of these two:
backup/restore
detach, copy, attach
If you don't have access to the O/S and can't get it, another option is to create the missing role(s) in the background as the copy runs. You have to catch it between the creation of the files and when it tries to reference the roles, but there are a few seconds in which to create them if you keep clicking execute - I managed to create 9 roles.
Unfortunately, you'll end up with the roles in another database too (while yours cannot be used) so those need to be deleted.
Of course, this is only an option when you really can't use the other method.
Though the answer which is using the backup technique solves the problem generally, after facing the same issue several times, I was able to trace down the root of the problem using the Event Viewer of Windows to that the Database Copy wizard, using the SQL Agent, will eventually create a Job for the agent to run, after which the Agent will run using its own credentials (i.e. the credentials that you can look up in Windows Services, in my case, NT Service\SQLAgent$SQL2014)
All you need to do is to go the folder where SQL Server creates DB files (e.g. C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA by default for SQL 2014) and give the SQL Agent windows user write/read access on the folder.
The reason can be that a file with the new Database name already exist on the filesystem. We encountered this when we renamed Database X to X_Old, and tried to copy database Y to X. This cannot be done, because database X_Old is still associated with the filename X.
Either delete the conflicting database, or rename the file on the file system.
See http://codecopy.wordpress.com/2012/01/03/error-while-copying-a-database/

Resources