SQL Server Copy Database Issue - sql-server

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/

Related

Not able to attach database in SQL Server 2008R2

I have SQL Server 2008R2 on my laptop, with a number of databases on it.
I detached one of my development databases today (I wanted to take a copy) using SSMS, and now I can't re-attach it. Whenever I try I get the following error
CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file
I have seen numerous similar questions on this, and they always seem to suggest the database being attached to another SQL Server instance. I have checked as to whether I have another SQL Server instance running, can't see anything even remotely like in Task manager. I even restarted the computer to clear any if they were there - no joy.
I read somewhere that if I change the Log On checkbox on the SQL Server Services properties Log On tab to Local System Account that should do it; it didn't.
I am at a complete loss as to where to go next.
Any ideas anyone?
Error 5 is Access Denied. It is a permissions issue. You do not have permissions to write to that location. You probably should be an Administrator on that machine.

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"

How do I change "Database default locations" for LocalDB in SQL Server Management Studio?

Connect to LocalDB in SSMS
Open Server Properties -> Database Settings
Change Data/Log/Backup locations -> click OK
When I click OK I get this error:
Found some blogpost and changed this in regedit but it didn't help.
Anyone got any other ideas I could try?
I do not believe that these default paths for SQL Server LocalDB are changeable. This is quite unfortunate due to what appears to be a bug with SQL Server Express 2017 LocalDB ** (fixed as of CU 6 for SQL Server 2017), as per this question (and my answer to it) on DBA.StackExchange:
LocalDB v14 creates wrong path for mdf files
HOWEVER, you do not need to use the default paths. Those are used when you create a Database without specifying the physical locations. If you specify the physical location, then you should be able to create the files to any folder / directory that you have read / write access to.
After making that change in the registry try restarting the sql instance.
Also I would make sure that the account running SQL Server has the ability to write to that folder.
for an easy test you could go to the folder properties -> security then add the account 'everyone' then give them full control. then try making that change. If it works it was a permissions issue to that account. Accounts generally don't have access to other users accounts without some level of admin.
After 10 years this is still an issue for the current version(15.0) of Microsoft SQL Server Express.
After a bit of investigation I discovered, there is an issue with permission inside the registry. The process sqlservr.exe cannot create entries in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL15E.LOCALDB\MSSQLServer.
On my computer this process is running under my account, so I opened regedit and gave myself Full Control permission to this key. And it worked like a charm. I hope this will help you as well.
Changing these paths in RegEdit or SSMS doesn't work, SQL LocalDb won't respect these values for existing databases. One has to move the databases manually. Here is the reliable way to change a database location for any LocalDB instance.
First, make sure you work with a correct instance of SQL Server LocalDB. In command prompt enter:
sqllocaldb info
It will show the LocalDB instances you have on your machine. Let's assume that the instance name is MSSQLLocalDB.
Next, execute this script on your database (let's call it TestApp), using SqlCmd tool or SSMS:
alter database TestApp
modify file (name = TestApp, filename = 'C:\NewDataLocation\TestApp.mdf');
go
alter database TestApp
modify file (name = TestApp_log, filename = 'C:\NewDataLocation\TestApp_log.ldf');
go
Now, stop the SQL LocalDB instance, in command prompt:
sqllocaldb stop MSSQLLocalDB
Move the database files to the new location that you specified in the script. From %UserProfile%\TestApp.mdf (which is where they are located) to C:\NewDataLocation\TestApp.mdf, same for LDF file.
Start the SQL LocalDB instance again:
sqllocaldb start MSSQLLocalDB
Now your database is working from a new location. Repeat the steps for any other databases.
Paths Cannot Be Changed in SQL Server LocalDB "Automatic Instance" Types
In case anyone in 2023 finds out they cannot change their default database file storage paths, this article is for you!
This error applies to Microsoft SQL Server not being able to allow you to change the default file folder location on your PC where the SQL Server Database Files are saved (database and logs files, .mdf and .ldf).
Most developers often need control over where local database files are saved. Most prefer to store them in a central location, another drive, or simply the main SQL Server database repository inside the C:\Program Files\Microsoft SQL Server\{sql version name}\MSSQL\DATA, since that is where system data storage goes. One example of the problem of not being able to customize database file storage might be using Entity Framework Core, which runs "migration" scripts that create databases in SQL Server. When it does so, where those scripted databases get stored is heavily dependent on SQL Server's default file path settings. When the location of those EF code-first database files using LocalDB is locked down, developers are stuck with SQL files in multiple locations on their PC's.
THE PROBLEM
Apparently, when Microsoft installs SQL Server / SQL Express on your device, it attempts to install a default instance of the server as a specialized type called a "LocalDB Automatic Instance". They do this to get the user up and running fast with a "LocalDB" sql server instance, which is a one-time, "light", custom created server running as a public instance, complete with default settings which are customized for the user (or developer) so he can get up and running fast. The automatic type has the advantage that its granted permissions to the user as administrator in SQL, as well as granting all applications on the user's device public access to the server instance. (You will notice that IIsExpress works this way using ApplicationPools as dummy Windows User Accounts, creating default accounts next to your User Account in Windows to run app pools in IIS.) These SQL Server LocalDB binaries do not run as a service but on-demand. But only one of the "automatic" types may be installed per version per device. The other SQL Server LocalDB type is the named instance and is not as restricted as the automatic one, apparently.
The problem is, when they create this special LocalDB automatic instance, it locks down certain settings and applies certain permissions and settings that are unique just for this instance. This then limits what the user can do as far as customizations, one of which is the "Database default locations" in the Properties dialog box that appears when you right-click your sql server instance and choose properties.
Anyone using the full SQL Server version, or who has created a new instance of LocalDB, deleting the old one, will not experience this issue, so most of those people are scratching their heads.
But for local developers, what this means is your Sql Server LocalDB databases running under this instance of the server will typically store their databases under a locked down path...either the path you chose on install or default to the user-friendly account paths under C:\Users\{YourName}.
When users attempt to change the path in the properties box for the instance, many users online the past 5-6 years have noticed a nasty RegCreateKeyEx() returned error 5 Access is denied that would appear when saving a default path. Microsoft doesn't bother to tell you, but that is intentional. They don't expect to allow you to save paths to the registry for the instance, and assume everyone is ok with the default path.
You can fix the key error by going into your registry and changing permission on the Microsoft SQL Server registry keys, assigning the "Everyone" group account to the registry node managing these keys. In the Registry, add Everyone group account to this node below then try and save a new default path in the properties box for your sql server localdb instance:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
The location of the default database file path keys (2019) in the Registry in Windows for an instance of the localdb server of are located here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL15E.LOCALDB\MSSQLServer
You are then able to save the new default paths in SQL, and the error goes away. Saving your default path in the Properties box works now, and the new values appear in the registry.
Even though you can change these paths, they will not stick, however, and reset back to the User Account Path, by default. Even if you save a new default sql path for your databases, when you create a new database it still reverts to the old path. Again, this applies ONLY for users who are running under the default "Automatic" LocalDB instance created on install of SQL Express.
So even after restarting SQL, restarting your PC, or restarting the SQL Service, those registry values will still not pull the registry keys into the SQL Server instance settings for Default file paths.
As proof, run these two scripts below in your SQL Server LocalDB instance. The first one returns the actual LocalDB default file paths SQL Server stores internally. The second script returns what is stored in your registry for the LocalDB default file path. If you saved new default path registry keys, they should be the same and shown in SQL Server instance properties, but they are different! That means Microsoft has decided not to allow you to change them for those running the "automatic" instance type of LocalDB on install. Below is the T-SQL to run to test this:
-- GETS THE PATH STORED IN SQL SERVER FOR "DefaultData" path
SELECT
[Value] = 'DefaultData',
[Data] = SERVERPROPERTY('InstanceDefaultDataPath')
-- DefaultData C:\Users\YourAccountName\
-- GETS WHATS IN THE REGISTRY FOR "DefaultData" path
EXECUTE [master].dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQLServer',
N'DefaultData'
-- DefaultData C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA
-- Note: If the second one returns `NULL` it just means you
-- have not yet tried or succeeded in saving a new file path
-- to your registry.
Why isnt SQL Server LocalDB pulling in the registry values?
What this means again, is sorry you can't change these default paths. Your best bet is to simple "detach" your databases, copy the .mdf and .ldf files to your new prefered folder, then reattach. When you create new databases, the console allows you to change the database file path there, as well. There are also some elaborate SQL scripts you can run to set paths before saving files.
But just know this is by design.
I think one of the purposes of LocalDB is that it is very convinient in bundling a demo database along with the source files of an application. The database file and its log, of course, are somewhere in the source file directory.
Take a Visual Studio solution for example, in web.config or app.config, you can see something like this:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-XXXXXX-20140609153630;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-XXXXXX-20140609153630.mdf" providerName="System.Data.SqlClient" />
Now that the location of every LocalDB is specified in the config file, I don't think "default location" makes much sense.

SQL Server Restore Error - Access is Denied

I created a database on my local machine and then did a backup called tables.bak of table DataLabTables.
I moved that backup to a remote machine without that table and tried to do a restore but get the following error:
System.Data.SqlClient.SqlError: The operating system returned the
error '5(Access is denied.)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'c:\Program
Files\Microsoft SQL Server\MSSQL.1\MSSQL\DataLabTables.mdf'.
How do I fix my rights, if that is the problem?
I have just had this issue with SQL Server 2012.
It turns out all I had to do was tick the box marked 'Relocate all files to folder' on the 'Files' section:
(Click to see image full size)
This of course assumes you have the correct version of SQL Server installed.
From the error message, it says there's an error when validating the target (c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DataLabTables.mdf) of your restore operation.
That sounds like:
a) that file already exists (because you've already restored it previously) and is in use by SQL Server
or
b) that directory doesn't exist at all
In your question, you mentioned you created a backup for that table - that's not how SQL Server backups work. Those backups are always the whole database (or at least one or several filegroups from that database).
My hunch is: you've already restored that database previously, and now, upon a second restore, you didn't check the checkbox "Overwrite existing database" in your restore wizard - thus the existing file cannot be overwritten and the restore fails.
The user that's running the restore on your remote server obviously doesn't have access to that directory on the remote server.
C:\program files\.... is a protected directory - normal (non-admin) users don't have access to this directory (and its subdirectories).
Easiest solution: try putting your BAK file somewhere else (e.g. C:\temp) and restore it from there
I was having the same problem. It turned out that my SQL Server and SQL Server Agent services logon as were running under the Network Services account which didn't have write access to perform the restore of the back up.
I changed both of these services to logon on as Local System Account and this fixed the problem.
Recently I faced this issue with SQL 2008 R2 and the below solution worked for me:
1) Create a new database with the same name as the one you are trying to restore
2) While restoring, use the same name you used above and in the options, click the overwrite option
You might give the above a shot if the other solutions don't work.
The backup creator had MSSql version 10 installed, so when he took the backup it also stores the original file path (to be able to restore it in same location), but I had version 11, so it could not find the destination directory.
So I changed the output file directory to C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\, and it was able to restore the database successfully.
Source
I had a similar problem. I tried to restore a 2005 .bak file, and i received exactly the same error. I selected the overwrite option as well to no avail.
my solution was to grant the SQL user access to the directory in question, by going to the folder and editing the access rights through the property screen.
lost a couple of hours to this problem too. got it going though:
"access denied" in my case really did mean "access denied". mssqlstudio's user account on my windows device did NOT have full control of the folder specified in the error message. i gave it full control. access was no longer denied and the restore succeeded.
why was the folder locked up for studio ? who knows ? i got enough questions to deal with as it is without trying to answer more.
I had this issue, I logged in as administrator and it fixed the issue.
Another scenario could be the existence of multiple database paths. First, make note of the path where new databases are currently being stored. So if you create a new empty database and then do Tasks/Restore, make sure that the path the restore is trying to use is the same directory that the empty database was created in. Even if the restore path is legal, you will still get the access denied error if it is not the current path you are working with. Very easy to spot when the path is not legal, much harder to spot when the path is legal, but not the current path.
Sorry because I cannot comment...
I had the same problem. In my case the problem was related to trying to restore in an old sql server folder (that existed on the server). This is due to old sql server backup (i.e. SQL Server 2012 Backup) restored in a new sql server (SQL Server 2014). The real issue is not too different from #marc_s answer. Anyway, I changed only the target folder to the new SQL Server DATA folder.
This may not be the best solution, but I was trying to do the restore at SQL Server 2005, but I changed to SQL Server 2008 and it worked.
Got problem like this. Error caused by enabled compression on SQL Server folders.
Frnds... I had the same issue while restroring database and tried every solution but could nt get resolved. Then i tried to re install SQL 2005 and the problem solved. Actully last time i forgot to check on customize option while instlling SQL.. It comes two times while installing and i checkd it for ones only..
In my case - I had to double check the Backup path of the database from where I was restoring. I had previously restored it from a different path when I did it the first time. I fixed the Backup path to use the backup path I used the first time and it worked!
I ended up making new folders for Data and Logs and it worked properly, must have been a folder/file permission issue.
This also happens if the paths are correct, but the service account is not the owner of the data files (yet it still has enough rights for read/write access). This can occur if the permissions for the files were reset to match the permissions of the folder (of course, while the service was stopped).
The easiest solution in this case is to detach each database and attach it again (because when attaching the owner is changed to be the service account).
Try this:
In the Restore DB wizard window, go to Files tab, Uncheck "Relocate All files to folder" check box then change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will get restored successfully.
I had the same problem but I used sql server 2008 r2, you must check in options and verify the paths where sql going to save the files .mdf and .ldf you must select the path of your sql server installation. I solved my problem with this, I hope it helps you.
Then try moving it to a sub folder under the C:, but verify that the user has full rights on the folder your use.

SQL Server 2008 database copy - file permissions

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

Resources