Backup Remote SQL database by building SQL Generate Scripts - sql-server

I have a VB.net application with an MS SQL Backend. I want to be able to take a "Snapshot" of the remote database so that the database can be cloned to another location. I want to do this by building SQL generate scripts similar to those created by SQL Management Studio. I found this code:
How to generate create script of tables with their constraints using SQL query in SQL Server 2008
which prints the scripts to the Messages window in SQL Studio express but I need it returned as the result so I can call it from my .Net application and get the scripts back so I can save them to a text file, ready to recreate the database elsewhere. Can anyone help?
The next stage of this task is scripting, then inserting all the data from the "Live" database. I know I can do all this using the Script Tools in SQL Studio but I need it built into my application, so my users can clone their Network Database locally to use away from the network.

The Options if you don't want to sync the server editions.
Upgrade the older version of SQL Server to be at the same level as the newer SQL Server.
Script out the objects from the newer database and then usp a bcp process to extract the data from the newer database and import it into the older database.
Use the SQL Server Import and Export Wizard to build an SSIS package to move the data (it will move the data only).
Build a custom SSIS package to do the data move.
Use replication to move the data from the newer database to the older one.
Use some other form of scripting, such as with PowerShell, to keep the databases in sync.
You should still want to use compressed database backups, you can then restore the database to end users with a smaller foot print. There are other options as well, like log shipping, database mirroring, and setting up availability groups. These all require more work than taking a compressed backup.
BACKUP DATABASE [Gigabits] TO DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\Gigabits.bak' WITH NOFORMAT, NOINIT, NAME = N'Gigabits-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10
GO
You cannot attach/detach or backup/restore a database from a newer version (SQL Server 2008 R2 - 10.50.1600) of SQL Server down to an older version (2008 - v10.00.1600) - the internal file structures are just too different to support backwards compatibility.
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.

Related

The database 'xxx' cannot be opened because it is version 904

I can't attach my database. When I try to attach a database in SQL Server Management Studio, I get this error:
The database 'C:\FILES\ACCOUNTING.MDF' cannot be opened because it is version 904. This server supports version 852 and earlier. A downgrade path is not supported. Could not open new database 'C:\FILES\ACCOUNTING.MDF'. CREATE DATABASE is aborted. (.Net SqlClient Data Provider)
and I have tried these commands:
cd "C:\Program Files\Microsoft SQL Server\130\LocalDB\Binn"
SqlLocalDB.exe delete "MSSQLLocalDB"
SqlLocalDB.exe create "MSSQLLocalDB"
but it still has an error
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server (v904 = SQL Server 2019) down to an older version (v852 which is SQL Server 2016) - the internal file structures are just too different to support backwards compatibility.
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The error message in the problem statement occurs because the SQL Server database files (*.mdf, *.ndf and *.ldf) and backups are not backward compatible. Backward compatibility is why we cannot restore or attach a database created from a higher version of SQL Server to a lower version of SQL Server. However, there are a few options that can help us to downgrade the database from a higher version of SQL Server to a lower version SQL Server. These options include:
Use the Generate Scripts Wizard in SQL Server Management Studio
Use SQL Server Integration Services
Create Custom Scripting and BCP
In this tip we will use the Generate Scripts Wizard in SQL Server Management Studio.
Here are the basic steps we need to follow:
Script the database schema and data from the higher version of SQL Server by using the Generate Scripts Wizard in SSMS.
Connect to the lower version of SQL Server, and run the SQL scripts that were generated in the previous step, to create the database schema and data.
In the next section, I will demonstrate the steps for downgrading a SQL Server 2012 database to SQL Server 2008 R2 database.
Steps to Downgrade a SQL Server Database Using SSMS Generate Scripts Wizard
Step 1 Script the schema of the OUTLANDER database on the SQL Server
2012 instance (IITCUK\DEV01) using the Generate Scripts wizard in
SSMS.
In Object Explorer connect to IITCUK\DEV01, right-click on the
OUTLANDER database, expand Tasks and choose "Generate Scripts...".
This launches Generate and Publish Scripts wizard. Click Next, to skip the Introduction screen and proceed to the Choose Objects page.
On the Choose Objects page, choose option "Script entire database and all database objects", and then click Next to proceed to "Set Scripting Options" page.
n the Advanced Scripting Options dialog box,
set Script for Server Version to SQL Server 2008 R2 (or whatever version you want)
under the Table/View Options, set Script Triggers, Script Indexes and Script Primary Keys to True
and set Types of data to script to Schema and Data - this last option is key because this is what generates the data per table.
Once done, click OK, to close the Advanced Scripting Options dialog box and return to Set Scripting Options page. In Set Scripting Options page, click Next to continue to Summary page.
After reviewing your selections on Summary page, click Next to generate scripts.
Once scripts are generated successfully, choose the Finish button to close the Generate and Publish Scripts wizard.
Step 2 Connect to the SQL Server 2008 R2 instance
(IITCUK\SQLSERVER2008), and then run the SQL scripts that were
generated in Step 1, to create the OUTLANDER database schema and data.
In Object Explorer connect to IITCUK\SQLServer2008, then in SQL Server
Management Studio, open the SQL Server script you saved in Step 1
Modify the script, to specify the correct location for the OUTLANDER database data and log files. Once done, run the script to create the OUTLANDER database on IITCUK\SQLServer2008 instance.
Upon successful execution, refresh the Database folder in Object Explorer. As you can see in the following image, the OUTLANDER database has been successfully downgraded.
Notes
There are a few things to be aware of when using this approach.
This solution creates one large SQL file that has the scripts to create the database objects and also INSERT statements for the data in the tables.
For a large databases, the SQL file can get very large if you script out both the schema and the data and could be hard to load into an editor. Also, you may get a memory related error message from the editor if the file is too big.
For large databases, around 1GB or more, if this approach does not work, then you should look at using SSIS to migrate the database or create custom scripts to script out the objects and BCP out the data for each of the tables. You can use this Generate Scripts wizard to just generate the schema without the data and use SSIS or BCP to export and import the data.
This approach works for SQL Server 2017 to SQL Server 2005. Some of the scripting options might be a bit different in newer versions, but the process is still the same.
Before just executing the script, you should review the script to make sure everything looks correct such as the path of the database files, database options, etc.
Also if you are using new functionality that does not exist in the lower version, SQL Server won't be able to create the objects and you will need to review the scripts that were generated and update the code accordingly.
For a very simple database this approach should work pretty easliy, but you might need to spend some time making some modifications to the script for a more complex database.
Below is a list of all of the scripting options. If you click on an item, the bottom part of the screen gives you a short definition of the option.
Next Steps
To avoid this issue, always make sure that you perform a full backup of the database before you upgrade the SQL Server and database to a higher version of SQL Server. In addition, be sure to thoroughly test the application prior to releasing the application to the users.
Consider this downgrade option as your last option to rollback from an upgrade because the time and storage needed can be very large.
With a very large database be sure you have sufficient storage to support the data needs.
Be sure to verify row and object counts as well as test your application before releasing to production.
Additional Resources:
Why Can't I Restore a Database to an Older Version of SQL Server?
SQL Server Database Engine Backward Compatibility
SQL Server Upgrade Tips

Mdf file is not attaching in Sql Server after data written in mdf file by windows application

I developed a windows based application where I use .mdf file for backend operations. When no data is passed through application into .mdf file that means a fresh .mdf file, I am able to attach this .mdf file in my SQL Server 2008 R2 successfully.
But when data is written into .mdf file through application, I am not able to attach that .mdf file. I am getting a SQL Server error:
Why version is changing automatically? Please help me
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version (706 = SQL Server 2012) of SQL Server down to an older version (661 = SQL Server 2008 R2) - the internal file structures are just too different to support backwards compatibility.
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.

Can I use one .mdf file with multiple DBMSes (SQL Server 2008 and 2012)?

At home, I have SQL Server 2008 R2 (Express) installed which is attached to a certain .mdf file. I'm in the process of installing SQL Server 2012 (Developer Edition). Can I attach 2012 to the same .mdf file? Logically, it seems like this would work as long as only one of the two instances of SQL Server is running. Thoughts?
You can go upwards - from an older version to a newer one, e.g. you can backup your database in 2008 R2 and restore that backup in your 2012 instance - but you CANNOT attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility.
Also: since the internal file structures of the .mdf are very much different and specific to each version of SQL Server, you will NOT be able to use the same .mdf from two different SQL Server versions. That definitely won't work.
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
It might work - but I believe you're going run in to some issues later down the road if the SQL 2012 updates the file in a technical manner that SQL 2008 blows up on.
Wouldn't it be simpler to run one copy and back up and restore to the other?

How to RESTORE a BACKUP from DB with different versions? [duplicate]

How to restore a higher version SQL Server database backup file onto a lower version SQL Server?
Using SQL Server 2008 R2 (10.50.1600), I made a backup file and now I want to restore it on my live server's SQL Server 2008 (10.00.1600).
When I tried to restore the backup onto SQL Server 2008 it gives an error i.e. Restore Failed because:
The database was backed up on a server running version 10.50.1600.
That version is incompatible with this server, which is running version
10.00.1600.
How do I restore the backup file on this server?
You can use functionality called Export Data-Tier Application which generates .bacpac file consisting database schema and data.
On destination server, you can use Import Data-Tier Application option which creates and populates new database from pre-created .bacpac file
If you want just to transfer database schema, you can use Extract Data-Tier Application for creating file and Deploy Data-Tier Application for deploying created database schema.
I've tried this process on different versions of SQL Server from SQL 2014 to SQL 2012 and from SQL 2014 to SQL 2008R2 and worked well.
No, is not possible to downgrade a database. 10.50.1600 is the SQL Server 2008 R2 version. There is absolutely no way you can restore or attach this database to the SQL Server 2008 instance you are trying to restore on (10.00.1600 is SQL Server 2008). Your only options are:
upgrade this instance to SQL Server 2008 R2 or
restore the backup you have on a SQL Server 2008 R2 instance, export all the data and import it on a SQL Server 2008 database.
You can not restore database (or attach) created in the upper version into lower version. The only way is to create a script for all objects and use the script to generate database.
select "Schema and Data" - if you want to Take both the
things in to the Backup script file select Schema Only -
if only schema is needed.
Yes, now you have done with the Create Script with Schema and Data of the Database.
Will not necessarily work
Backup / Restore - will not work when the target is an earlier MS SQL version.
Copy Database - will not work when the target is SQL Server Express: "The destination server cannot be a SQL Server 2005 or later Express instance."
Data import - Will not copy the schema.
Will work
Script generation - Tasks -> Generate Scripts. Make sure you set the desired target SQL Server version on the Set Scripting Options -> Advanced page. You can also choose there whether to copy schema, data, or both. Note that in the generated script, you may need to change the DATA folder for the mdf/ldf files if moving from non-express to express or vice versa.
Microsoft SQL Server Database Publishing Services - comes with SQL Server 2005 and above, I think. Download the latest version from here. Prerequisites: sqlncli.msi/sqlncli_x64.msi/sqlncli_ia64.msi, SQLServer2005_XMO.msi/SQLServer2005_XMO_x64.msi/SQLServer2005_XMO_ia64.msi (download here).
Here are my 2 cents on different options for completing this:
Third party tools: Probably the easiest way to get the job done is to create an empty database on lower version and then use third party tools to read the backup and synchronize new newly created database with the backup.
Red gate is one of the most popular but there are many others like ApexSQL Diff , ApexSQL Data Diff, Adept SQL, Idera …. All of these are premium tools but you can get the job done in trial mode ;)
Generating scripts: as others already mentioned you can always script structure and data using SSMS but you need to take into consideration the order of execution. By default object scripts are not ordered correctly and you’ll have to take care of the dependencies. This may be an issue if database is big and has a lot of objects.
Import and export wizard: This is not an ideal solution as it will not restore all objects but only data tables but you can consider it for quick and dirty fixes when it’s needed.
Another way to do this is to use "Copy Database" feature:
Find by right clicking the source database > "Tasks" > "Copy Database".
You can copy the database to a lower version of SQL Server Instance. This worked for me from a SQL Server 2008 R2 (SP1) - 10.50.2789.0 to Microsoft SQL Server 2008 (SP2) - 10.0.3798.0
You can try this.
Create a Database onto SQL Server 2008.
Using Import Data feature import data from SQL Server R2 (or any higher version).
use "RedGate SQLCompare" to synchronize script.
Go to Task->Generate Scripts...
In Advanced in "Types of data for script" select "Schema and data" and try to run this script in your lower version.
It's not pretty, but this is how I did it granted you have this option installed on your SQL 2008 R2 install..
1) Right click database in SQL Server 2008 R2 "Tasks".. "Generate scripts" in the wizard, select the entire database and objects in first step. On the "Set Scripting Options" step you should see a button "Advanced" , select this and make sure you select "Script for Server Version" = SQL Server 2008" not R2 version.
This is a crucial step, because "import data" by itself does not bring along all the primary keys, constriants and any other objects like stored procedures."
2) Run the SQL script generated on the new install or database instance SQL Express or SQL Server 2008 using the query window or open saved .sql script and execute and you should see the new database.
3) Now right click on the new database and select "Tasks".. "Import Data.." choose source as the R2 database and the destination as the new database. "Copy data from one or more tables or views", select the top checkbox to select all tables and then next step, run the package and you should have everything on a older version. This should work for going back to a 2005 version as well. Hope this helps someone out.
you can use BCP in and out for small tables.
BCP OUT command:-
BCP "SELECT * FROM [Dinesh].[dbo].[Invoices]" QUERYOUT C:\av\Invoices1.txt -S MC0XENTC -T -c -r c:\error.csv
BCP IN command:-
Create table structure for Invoicescopy1.
BCP [Dinesh].[dbo].[Invoicescopy1] IN C:\av\Invoices.txt -S MC0XENTC -T -c
I appreciate this is an old post, but it may be useful for people to know that the Azure Migration Wizard (available on Codeplex - can't link to is as Codeplex is at the moment I'm typing this) will do this easily.
You'd have to use the Import/Export wizards in SSMS to migrate everything
There is no "downgrade" possible using backup/restore or detach/attach. Therefore what you have to do is:
Backup the database from the server running the new SSMS/SQL version.
Import data from the generated .bak file, by expanding the "Tasks" menu(after right-clicking the target database) and selecting the "Import Data" option.
You can generate script from Task menu
For detailed reference
How to migrate a SQL Server database to a lower version

How do I backup the data in SQL Server 2008 on a third party host?

I have a SQL Server 2008 database that is hosted by a third party host (heart internet).
How would I go about backing this up?
I used SQL Server Management Studio Express 2008 to create the tables within the database, but the backup options within this app seem to be only of use if you have direct access to the server machine (which I don't)
It's also worth noting that I am using change tracking - I presume this data would be lost should any backup be restored?
Thanks In Advance!
(PS - SQL Server 2008 novice here!)
If they allow you to run backups to a particular folder that you have access to you can just do it with the regular backup command:
backup database dbname to disk = 'y:\users\YourHomePath'
If they do not do that you might want to use the Database Publishing Wizard to script out your database (depending on the size this might be very slow)
You can create a .DAT file into a shared disk and to download it through FTP.

Resources