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

二次信任 提交于 2019-12-20 10:04:46

问题


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.


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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




回答5:


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




回答6:


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!



来源:https://stackoverflow.com/questions/5477117/how-can-i-generate-a-script-of-my-database-as-it-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!