简体   繁体   English

如何在 SQL Server Management Studio 2008 中自动执行“生成脚本”任务?

[英]How can I automate the “generate scripts” task in SQL Server Management Studio 2008?

I'd like to automate the script generation in SQL Server Management Studio 2008.我想在 SQL Server Management Studio 2008 中自动生成脚本。

Right now what I do is :现在我做的是:

  • Right click on my database, Tasks, "Generate Scripts..."右键单击我的数据库,任务,“生成脚本...”
  • manually select all the export options I need, and hit select all on the "select object" tab手动选择我需要的所有导出选项,然后在“选择对象”选项卡上点击全选
  • Select the export folder选择导出文件夹
  • Eventually hit the "Finish" button最终点击“完成”按钮

Is there a way to automate this task?有没有办法自动化这个任务?

Edit : I want to generate creation scripts, not change scripts.编辑:我想生成创建脚本,而不是更改脚本。

SqlPubwiz has very limited options compared to the script generation in SSMS.与 SSMS 中的脚本生成相比,SqlPubwiz 的选项非常有限。 By contrast the options available with SMO almost exactly match those in SSMS, suggesting it is probably even the same code.相比之下, SMO可用的选项几乎与 SSMS 中的选项完全匹配,这表明它甚至可能是相同的代码。 (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. (我希望MS没写两次!)有MSDN上几个例子像这一次,显示脚本表作为单独的对象。 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.但是,如果您希望所有内容都使用包含“DRI”(声明性引用完整性)对象(如外键)的“完整”模式正确编写脚本,则单独编写表的脚本无法正确处理依赖项。 I found it is neccessary to collect all the URNs and hand them to the scripter as an array.我发现有必要收集所有 URN 并将它们作为数组交给脚本编写者。 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();

What Brann is mentioning from the Visual Studio 2008 SP1 Team Suite is version 1.4 of the Database Publishing Wizard. Brann 在 Visual Studio 2008 SP1 Team Suite 中提到的是数据库发布向导的 1.4 版。 It's installed with sql server 2008 (maybe only professional?) to \\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\1.4.它随 sql server 2008(可能只是专业版?)一起安装到 \\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\1.4。 The VS call from server explorer is simply calling this.来自服务器资源管理器的 VS 调用只是调用它。 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.我不知道 v1.4 是否和 v1.1 有同样的问题(用户被转换为角色,约束没有按正确的顺序创建),但这对我来说不是一个解决方案,因为它没有脚本对象到不同的文件,如 SSMS 中的 Tasks->Generate Scripts 选项。 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).我目前正在使用 Scriptio 的修改版本(使用 MS SMO API)作为数据库发布向导 (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. Scriptio 最初发布在 Bill Graziano 的博客上,但随后由 Bill 发布到 CodePlex 并由其他人更新。 Read the discussion to see how to compile for use with SQL Server 2008.阅读讨论以了解如何编译以用于 SQL Server 2008。

http://scriptio.codeplex.com/ http://scriptio.codeplex.com/

EDIT: I've since started using RedGate's SQL Compare product to do this.编辑:我已经开始使用 RedGate 的 SQL 比较产品来做到这一点。 It's a very nice replacement for all that sql publishing wizard should have been.它是 sql 发布向导本应具备的所有功能的非常好的替代品。 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.它恰好与他们的其他产品 SQL Source Control 使用的格式相同。

I wrote an open source command line utility named SchemaZen that does this.我编写了一个名为SchemaZen 的开源命令行实用程序来执行此操作。 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

You can use SQL Server Management Object (SMO) to automate SQL Server 2005 management tasks including generating scripts:您可以使用 SQL Server 管理对象 (SMO) 自动执行 SQL Server 2005 管理任务,包括生成脚本: http://msdn.microsoft.com/en-us/library/ms162169.aspx . http://msdn.microsoft.com/en-us/library/ms162169.aspx

If you're a developer, definitely go with SMO.如果您是开发人员,请务必使用 SMO。 Here's a link to the Scripter class, which is your starting point:这是 Scripter 类的链接,这是您的起点:

Scripter Class脚本类

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:我没有看到这些答案中提到的带有 SQLPSX 的 powershell ......我个人没有玩过它,但它看起来非常简单易用,非常适合此类自动化任务,任务如下:

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 ) (参考: http : //www.sqlservercentral.com/Forums/Topic1167710-1550-1.aspx#bm1168100

Project page: http://sqlpsx.codeplex.com/项目页面: 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.这种方法的主要优点是它结合了直接使用 SMO 的可配置性/可定制性,以及使用简单的现有工具(如数据库发布向导)的便利性和可维护性。

在“工具”>“选项”>“设计器”>“表和数据库设计器”中,有一个“自动生成更改脚本”选项,该选项将为您在保存时所做的每个更改生成一个。

You can do it with T-SQL code using the INFORMATION_SCHEMA tables.您可以通过使用 INFORMATION_SCHEMA 表的 T-SQL 代码来完成。

There are also third-party tools - I like Apex SQL Script for precisely the use you are talking about.还有第三方工具 - 我喜欢 Apex SQL Script 正是因为您正在谈论的用途。 I run it completely from the command-line.我完全从命令行运行它。

If you want to a Microsoft solution you can try: Microsoft SQL Server Database Publishing Wizard 1.1如果您想要 Microsoft 解决方案,您可以尝试:Microsoft SQL Server Database Publishing Wizard 1.1

http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en 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.它创建了一个批处理,您可以在需要重建脚本的任何时候运行。

Try new SQL Server command line tools to generate T-SQL scripts and monitor Dynamic Management Views.尝试新的 SQL Server 命令行工具来生成 T-SQL 脚本并监控动态管理视图。

Worked for me like charm.像魅力一样为我工作。 It is a new python based tool from Microsoft that runs from command line.它是来自 Microsoft 的一个新的基于 Python 的工具,可从命令行运行。 Everything works like described on the Microsoft page (see link below) Worked for me with SQL 2012 server.一切都像 Microsoft 页面上描述的一样(见下面的链接) 使用 SQL 2012 服务器为我工作。

You install it with pip:你用 pip 安装它:

$pip install mssql-scripter $pip 安装 mssql 脚本程序

Command parameter overview as usual with h for help:命令参数概览照常使用 h 寻求帮助:

mssql-scripter -h mssql 脚本程序 -h

Hint: If you log in to SQL-Server via Windows authentication, just leave away Username and password.提示:如果您通过 Windows 身份验证登录 SQL-Server,只需留下用户名和密码。

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/ https://cloudblogs.microsoft.com/sqlserver/2017/05/17/try-new-sql-server-command-line-tools-to-generate-t-sql-scripts-and-monitor-dynamic-management-观看次数/

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 .我一直在使用 DB 比较器 - 它是免费的,没有大惊小怪的整个 DB 脚本,可以与另一个 DB 进行比较,还可以生成一个 Diff 脚本。 Excellent for Development to Production change scripts.非常适合开发到生产更改脚本。 http://www.dbcomparer.com/ http://www.dbcomparer.com/

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/ 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.一切都存储在文件夹和单独的 sql 文件中,以便于文件比较。

Code is also available on github.代码也可以在 github 上找到。

I am using VS 2012(for DBs on MSSQL Server 2008) compare database has an option to save it, the comparison and options.我正在使用 VS 2012(用于 MSSQL Server 2008 上的数据库)比较数据库有一个选项来保存它,比较和选项。 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.我只是觉得稍后从文件加载它有点尴尬(从 Windows 资源管理器拖放),因为我没有在解决方案资源管理器中看到该文件。

From Visual Studio 2008 SP1 TeamSuite :从 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.在服务器资源管理器/数据连接选项卡中,有一个发布到提供程序工具,它​​的作用与“Microsoft SQL Server 数据库发布向导”相同,但与 MS Sql Server 2008 兼容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Microsoft SQL Server 2008 Management Studio中仅将数据库中的索引生成到sql文件中? - How can I generate only indexes from a database into a sql file in Microsoft SQL Server 2008 Management Studio? 有没有办法从Microsoft SQL Server Management Studio的查询窗口(任务)生成脚本? - Is there a way to (task) generate scripts from query window in Microsoft SQL Server Management Studio? 在Management Studio中使用Python自动执行“生成脚本”选项,以从本地SQL Server获取数据并将其保存在.sql文件中 - Using Python to Automate “Generate Scripts” option in Management Studio to get the data from local SQL Server and save it in a .sql file 我可以在 SQL Server 2005 任务中自动“生成脚本”吗? - Can I automatically 'Generate Scripts' in a SQL Server 2005 task? SQL Server 2016 Management Studio - 为Generate Scripts选择错误的源代码 - SQL Server 2016 Management Studio - Picking wrong source for Generate Scripts 生成脚本SQL Server 2008 - Generate scripts SQL Server 2008 如何在SQL Server 2008 Express中使用SQL Server Management Studio启用全文索引? - How can I enable Full-Text indexing using SQL Server Management Studio in SQL Server 2008 Express? 无法在SQL Management Studio中从LocalDB生成脚本 - Can't generate scripts from LocalDB in SQL Management Studio SQL Server管理Studio 2008 - sql server management studio 2008 如何生成脚本以使用SQL Server Management Studio [架构和数据]重新创建表? - How to generate scripts to recreate table using SQL Server Management Studio [Schema and data]?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM