18 Nov SQL Server: Copy database from recent to older versions
Recently, I needed to copy a database from SQL Server 2012 to SQL Server 2008 R2. Unfortunately, database backups from one version of SQL Server cannot be read by a lower version. To work around this, I had to use the “Generate Scripts” function to first create the structure and then populate the database.
Whilst none of this is particularly complex, I thought it might be useful to collate the steps in one document…
Step 1: Generate structure scripts
- In the SQL Server instance that contains the database to copy, right-click on the Database in the Object Explorer, select Tasks, then select Generate Scripts.
- In the Wizard, progress to Choose Objects and make sure that “Script entire databases and all database objects” is selected.
- Progress to the “Set Scripting Options” stage. Click on “Advanced” and make sure that the “Type of data to script” option is set to “Schema only”. Also set the “Script for Server Version” option to the other SQL Server’s version (I still ran into incompatibility problems with the generated script, however).
- Finish off the Wizard, copy the generated scripts to a location that the other SQL Server instance can access and run them in that Management Studio. Here are the main problems and fixes I ran into during this part of the process:
- Error message that “CONTAINMENT is marked as incorrect syntax”: Just comment out the “CONTAINMENT = NONE” line (source: http://stackoverflow.com/a/15410854)
- Error message that CREATE Database commands can’t be run in a multi-transaction statement: Just run the create statement separately.
- Error when trying to alter user to add role: This command is not supported in older versions; change those commands to use “sp_addrolemember” (e.g. EXEC sp_addrolemember ‘db_datareader’, ‘Administrator’) (source: http://technet.microsoft.com/en-us/library/ms187750.aspx).
- If that all goes well, you should now have the database skeleton ready. The next step is to import the data.
- Back on the originating SQL Server, go to Generate Scripts again, but this time in the Advanced options, set “Type of data to script” to “Data only”. Because this will probably require a lot of space, in the “Set Scripting Options” screen, set “Files to generate” to “Single file per object”, to split up all of the scripts by table. Finish the Wizard.
- You should now have a bunch of script files, ready to be run. Copy the containing directory to a location the older SQL Server can access. Because I had 219 generated files, to save on running them manually, I used the following batch script (create and run it from the containing folder):
for %%G in (*.sql) do sqlcmd /S servername /d databaseName -E -i"%%G" pause
(source: http://stackoverflow.com/a/6504317)
- The above script may take a while to run, but after that, you should be done!