如何在 SQLServerManagementStudio2008中自动执行“生成脚本”任务?

我想在 SQLServerManagementStudio2008中自动生成脚本。

现在我要做的是:

  • 右键单击我的数据库,任务,“生成脚本...”
  • 手动选择我需要的所有导出选项,然后在“ select object”选项卡上点击 select all
  • 选择导出文件夹
  • 最终点击“完成”按钮

有没有办法使这项任务自动化?

编辑: 我想生成 创造脚本,而不是更改脚本。

96767 次浏览

In Tools > Options > Designers > Table and Database Designers there's an option for 'Auto generate change scripts' that will generate one for every change you make at the time you save it.

You can do it with T-SQL code using the INFORMATION_SCHEMA tables.

There are also third-party tools - I like Apex SQL Script for precisely the use you are talking about. I run it completely from the command-line.

You can use SQL Server Management Object (SMO) to automate SQL Server 2005 management tasks including generating scripts: http://msdn.microsoft.com/en-us/library/ms162169.aspx.

If you want to a Microsoft solution you can try: Microsoft SQL Server Database Publishing Wizard 1.1

http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en

It create a batch process you can run anytime you need to rebuild the scripts.

If you're a developer, definitely go with SMO. Here's a link to the Scripter class, which is your starting point:

Scripter Class

From Visual Studio 2008 SP1 TeamSuite :

In the Server Explorer / Data Connections tab, there's a publish to provider tool which does the same as "Microsoft SQL Server Database Publishing Wizard", but which is compatible with MS Sql Server 2008.

What Brann is mentioning from the Visual Studio 2008 SP1 Team Suite is version 1.4 of the Database Publishing Wizard. It's installed with sql server 2008 (maybe only professional?) to \Program Files\Microsoft SQL Server\90\Tools\Publishing\1.4. The VS call from server explorer is simply calling this. You can achieve the same functionality via the command line like:

sqlpubwiz help script

I don't know if v1.4 has the same troubles that v1.1 did (users are converted to roles, constraints are not created in the right order), but it is not a solution for me because it doesn't script objects to different files like the Tasks->Generate Scripts option in SSMS does. I'm currently using a modified version of Scriptio (uses the MS SMO API) to act as an improved replacement for the database publishing wizard (sqlpubwiz.exe). It's not currently scriptable from the command line, I might add that contribution in the future.

Scriptio was originally posted on Bill Graziano's blog, but has subsequently been released to CodePlex by Bill and updated by others. Read the discussion to see how to compile for use with SQL Server 2008.

http://scriptio.codeplex.com/

EDIT: I've since started using RedGate's SQL Compare product to do this. It's a very nice replacement for all that sql publishing wizard should have been. You choose a database, backup, or snapshot as the source, and a folder as the output location and it dumps everything nicely into a folder structure. It happens to be the same format that their other product, SQL Source Control, uses.

I don't see powershell with SQLPSX mentioned in any of these answers... I personally haven't played with it but it looks beautifully simple to use and ideally suited to this type of automation tasks, with tasks like:

Get-SqlDatabase -dbname test -sqlserver server | Get-SqlTable | Get-SqlScripter | Set-Content -Path C:\script.sql
Get-SqlDatabase -dbname test -sqlserver server | Get-SqlStoredProcedure | Get-SqlScripter
Get-SqlDatabase -dbname test -sqlserver server | Get-SqlView | Get-SqlScripter

(ref: http://www.sqlservercentral.com/Forums/Topic1167710-1550-1.aspx#bm1168100)

Project page: http://sqlpsx.codeplex.com/

The main advantage of this approach is that it combines the configurablity / customizability of using SMO directly, with the convenience and maintainability of using a simple existing tool like the Database Publishing Wizard.

I've been using DB Comparer - Its free and no fuss script entire DB and can compare to another DB and also produce a Diff script . Excellent for Development to Production change scripts. http://www.dbcomparer.com/

SqlPubwiz has very limited options compared to the script generation in SSMS. By contrast the options available with SMO almost exactly match those in SSMS, suggesting it is probably even the same code. (I would hope MS didn't write it twice!) There are several examples on MSDN like this one that show scripting tables as individual objects. However if you want everything to script correctly with a 'full' schema that includes 'DRI' (Declarative Referential Integrity) objects like foreign keys then scripting tables individually doesn't work the dependencies out correctly. I found it is neccessary to collect all the URNs and hand them to the scripter as an array. This code, modified from the example, works for me (though I daresay you could tidy it up and comment it a bit more):

    using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Sdk.Sfc;
// etc...


// Connect to the local, default instance of SQL Server.
Server srv = new Server();


// Reference the database.
Database db = srv.Databases["YOURDBHERE"];


Scripter scrp = new Scripter(srv);
scrp.Options.ScriptDrops = false;
scrp.Options.WithDependencies = true;
scrp.Options.Indexes = true;   // To include indexes
scrp.Options.DriAllConstraints = true;   // to include referential constraints in the script
scrp.Options.Triggers = true;
scrp.Options.FullTextIndexes = true;
scrp.Options.NoCollation = false;
scrp.Options.Bindings = true;
scrp.Options.IncludeIfNotExists = false;
scrp.Options.ScriptBatchTerminator = true;
scrp.Options.ExtendedProperties = true;


scrp.PrefetchObjects = true; // some sources suggest this may speed things up


var urns = new List<Urn>();


// Iterate through the tables in database and script each one
foreach (Table tb in db.Tables)
{
// check if the table is not a system table
if (tb.IsSystemObject == false)
{
urns.Add(tb.Urn);
}
}


// Iterate through the views in database and script each one. Display the script.
foreach (View view in db.Views)
{
// check if the view is not a system object
if (view.IsSystemObject == false)
{
urns.Add(view.Urn);
}
}


// Iterate through the stored procedures in database and script each one. Display the script.
foreach (StoredProcedure sp in db.StoredProcedures)
{
// check if the procedure is not a system object
if (sp.IsSystemObject == false)
{
urns.Add(sp.Urn);
}
}


StringBuilder builder = new StringBuilder();
System.Collections.Specialized.StringCollection sc = scrp.Script(urns.ToArray());
foreach (string st in sc)
{
// It seems each string is a sensible batch, and putting GO after it makes it work in tools like SSMS.
// Wrapping each string in an 'exec' statement would work better if using SqlCommand to run the script.
builder.AppendLine(st);
builder.AppendLine("GO");
}


return builder.ToString();

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

There is also this simple command line tool I build for my needs.
http://mycodepad.wordpress.com/2013/11/18/export-ms-sql-database-schema-with-c/

It can export an entire db, and it tries to export encrypted objects. Everything is stored in folders and separate sql files for easy file comparison.

Code is also available on github.

I am using VS 2012(for DBs on MSSQL Server 2008) compare database has an option to save it, the comparison and options. This is essentially what are your settings for delivery. After that you can do update or generate script.

I just find it it a little bit awkward to load it from file later(drag and drop from windows explorer) as I do not see the file in solution explorer.

Try new SQL Server command line tools to generate T-SQL scripts and monitor Dynamic Management Views.

Worked for me like charm. It is a new python based tool from Microsoft that runs from command line. Everything works like described on the Microsoft page (see link below) Worked for me with SQL 2012 server.

You install it with pip:

$pip install mssql-scripter

Command parameter overview as usual with h for help:

mssql-scripter -h

Hint: If you log in to SQL-Server via Windows authentication, just leave away Username and password.

https://cloudblogs.microsoft.com/sqlserver/2017/05/17/try-new-sql-server-command-line-tools-to-generate-t-sql-scripts-and-monitor-dynamic-management-views/