How can I generate a script of my database as it is? - sql-server

My primary reason for this is to keep track of database schema changes for my application. In SQL Server Management Studio I am able to generate a create script which creates the database but it doesn't contain any test data. Ideally when the script is run it should DROP the existing database (assuming it already exists) and then recreating it using this new script containing schema changes and test data from my development machine.
So how can I generate a script that will create a database with all the tables, stored procs, triggers, views, test data, etc?
I've tried using the import/export functionality but that's no good because it doesn't seem to copy over stored procedures. Plus it would be nice to have a script so I can track changes to the schema using mercurial.
I am using SQL Server Express 2008 R2 along with SQL Server Management Studio.

You didn't mention which version of SQL Server, but in SQL 2008 this is very easy
SQL 2008
Expand Databases
Right Click Database
Choose Tasks > Generate Scripts
Generate and
Publish Dialog will open Choose your
objects (i.e. Tables, procs, etc)
Click Next On the Set Scripting
Options choose Advanced Options Under
General choose SCRIPT DROP AND
CREATE - SCRIPT DROP AND CREATE
Types of Data To Script - Schema and
Data Close Advanced Window Choose to
save to file.

I wrote an open source command line utility named SchemaZen that does this. It's much faster than scripting from management studio and it's output is more version control friendly. It supports scripting both schema and data.
To generate scripts run:
schemazen.exe script --server localhost --database db --scriptDir c:\somedir
Then to recreate the database from scripts run:
schemazen.exe create --server localhost --database db --scriptDir c:\somedir

Try Microsoft SQL Server Database Publishing Wizard. This is a powerful flexible tool for scripting schema / data rom SQL Server.

Personally I use Microsoft Visual Studio 2010 Database Project with a Source Control Repository (SVN) to track changes to the schema.

Watch out for difference in database collation. If you develop on a database with a case insensitive collation and try and run the SSMS generated scripts against as database with a case sensitive collation then errors in case will break the scripts.

Usually i make backups fom a database before start a new development on it.
the best way is restore the backup when needed, i don't know how to get it by the script way!

Related

How to migrate the schema of a SQL Server database from on-premise to SQL Server on AWS RDS with non-supported features

I'm working on taking a on-premise server that works with SQL Server 2019 and migrating this to the cloud. The data right now is not the important thing, but rather the schema since this is a proof of concept. The main issue is that the on-premise server uses filestream to sometimes handle files. This will have to change in the future as refactoring and application updates take place.
The easiest way I thought would be to generate a schema .sql script from the old db and run that in the new environment, but this generated a TON of errors (25k).
Most of the errors include:
Failed permissions in database 'master'
Not finding certain objects in the new clean DB
Extended properties are not permitted on an object or it doesn't exist
Invalid data types
Database doesn't exist or permission not allowed
Filestream feature is disabled
So this probably won't work as a drop in solution to get the schema migrated to the new db. I've heard about AWS DMS (data migration service), but I don't know a lot about this. I'm asking, what tools could I look into to migrate over to RDS when RDS doesn't support features native to SQL Server?
One way to import schema is through the generated scripts wizard. You will have to manually tweak some things to make filestream and the local configuration of the sql server work nicely with aws RDS.
Generate and Publish Scripts Guide
Go to the source database
Right click the database in the menu on
the left (Object Explorer) Tasks>Generate Scripts
Select All tables,
procedures, etc.. except for filestream tables.
In the Scripts wizard pop up under Set Scripting Options, choose to make a .sql file, under advanced options, choose Schema Only. This will generate a script with only meta data for the tables and not the data in them
Generate the file.
Copy the .sql file over to the
EC2 instance (probably the Bastion Host) that is connected to the
RDS instance.
Open MS SQL Management Studio and right click on the
top most object in the Object Explorer and open a new query.
Copy and paste the code inside the .sql file into the query window.
Change the file path location of the data and log file to be
D:\rdsdbdata\DATA\TEST_AWS.mdf and D:\rdsdbdata\DATA\TEST_AWS_Log.ldf 
respectively. Any other file location will not be recognized by RDS
and will fail to create the table.
Comment or remove the lines of code that include:
a. ALTER DATABASE [TEST_AWS] SET TRUSTWORTHY OFF  
b. ALTER DATABASE [TEST_AWS] SET HONOR_BROKER_PRIORITY 
c. ALTER DATABASE [TEST_AWS] SET DB_CHAINING OFF Creating global users
d. FileStream
Execute the Script
Consider adding towards the top of the script DROP DATABASE [TEST_AWS] before the creation of the new database just in case you need to run the script multiple times to find the errors. This will save you from overwriting errors or having a unfinished table in memory.

Create Sql server 2008 Huge database script

I have a about 250 SQL script files included tables, stored procedure, user define function, triggers scripts.
I use these files to create and update old database. i want to enhance the time of creation cause it takes very long time to complete. is there more efficient way to create new database with all needed script indexes, triggers, views, SP, UDF.. or way to speed up the creation time.
Just import the scripts into a New SQL Server Database Project in Visual Studio and do a 'Deploy' of the Database Projects after setting up the connection strings properly.
See:
How to: Import Database Objects from a Script. and
Creating A Sql Server Database Project In Visual Studio 2012..
Are you using SQL Server Data Tools? These tools allow you to point your Visual Studio solution at a DB instance and it will generate you a Diff file, based on your DB projects contents.

Copy entire database contents (schema and data)

I need to copy the contents (tables, views, procs, DATA, etc.) of a SQL Server database and copy it to another SQL Server database. I need to do this entirely in a script as I am not able to carry over files to the destination web server. Using Microsoft SQL Server Management Studio, how can I accomplish this?
Note: The database I am copying to will have the same name and be completely empty.
You can script the database schema and data using SSMS
Right click on the database. Choose tasks....then choose generate sql scripts.
Specify all objects. Then in the options menu choose at the bottom to generate scripts for data.
Below are some links that will be helpful
http://blog.sqlauthority.com/2007/08/21/sql-server-2005-create-script-to-copy-database-schema-and-all-the-objects-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/
http://blog.sqlauthority.com/2007/11/16/sql-server-2005-generate-script-with-data-from-database-database-publishing-wizard/
You can backup the database and restore to any instance you'd like. Since I don't like posting the "how to" when I learned it someplace else originally - here's the MSDN describing the process.
http://msdn.microsoft.com/en-us/library/ms187048.aspx
It is how we do things in our production environment. We back up and restore to our other instances.
The easiest way would be to restore from a backup, but since you can't copy files to the file system, the Copy database wizard will do this.
http://msdn.microsoft.com/en-us/library/ms188664.aspx

Copy table to a different database on a different SQL Server

I would like to copy a table from one database to another. I know you can easily do the following if the databases are on the same SQL Server.
SELECT * INTO NewTable FROM existingdb.dbo.existingtable;
Is there any easy way to do this if the databases are on two different SQL Servers, without having to loop through every record in the original table and insert it into the new table?
Also, this needs to be done in code, outside of SQL Server Management Studio.
Yes. add a linked server entry, and use select into using the four part db object naming convention.
Example:
SELECT * INTO targetTable
FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]
If it’s only copying tables then linked servers will work fine or creating scripts but if secondary table already contains some data then I’d suggest using some third party comparison tool.
I’m using Apex Diff but there are also a lot of other tools out there such as those from Red Gate or Dev Art...
Third party tools are not necessary of course and you can do everything natively it’s just more convenient. Even if you’re on a tight budget you can use these in trial mode to get things done….
Here is a good thread on similar topic with a lot more examples on how to do this in pure sql.
SQL Server(2012) provides another way to generate script for the SQL Server databases with its objects and data. This script can be used to copy the tables’ schema and data from the source database to the destination one in our case.
Using the SQL Server Management Studio, right-click on the source database from the object explorer, then from Tasks choose Generate Scripts.
In the Choose objects window, choose Select Specific Database Objects to specify the tables that you will generate script for, then choose the tables by ticking beside each one of it. Click Next.
In the Set Scripting Options window, specify the path where you will save the generated script file, and click Advanced.
From the appeared Advanced Scripting Options window, specify Schema and Data as Types of Data to Script. You can decide from here if you want to script the indexes and keys in your tables. Click OK.
Getting back to the Advanced Scripting Options window, click Next.
Review the Summary window and click Next.
You can monitor the progress from the Save or Publish Scripts window. If there is no error click Finish and you will find the script file in the specified path.
SQL Scripting method is useful to generate one single script for the tables’ schema and data, including the indexes and keys. But again this method doesn’t generate the tables’ creation script in the correct order if there are relations between the tables.
Microsoft SQL Server Database Publishing Wizard will generate all the necessary insert statements, and optionally schema information as well if you need that:
http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A
Generate the scripts?
Generate a script to create the table then generate a script to insert the data.
check-out SP_ Genereate_Inserts for generating the data insert script.
Create the database, with Script Database as... CREATE To
Within SSMS on the source server, use the export wizard with the destination server database as the destination.
Source instance > YourDatabase > Tasks > Export data
Data Soure = SQL Server Native Client
Validate/enter Server & Database
Destination = SQL Server Native Client
Validate/enter Server & Database
Follow through wizard

sqlserver express database copy options

Why can I not see an option for copying database objects when I right click > tasks on my database?
MS Sql Server Express doesn't come with SSIS which is what you will need to import/export objects out of your database.
You can also manually script this process. One way is to use BCP (http://msdn.microsoft.com/en-us/library/ms162802.aspx)
Have a look at Red Gate SQL Compare and SQL Data Compare.
You can download the trial and use them to build a script that will dump your objects to a .sql file.

Resources