【问题标题】:Create script for table using GO Statement using SMO使用 SMO 使用 GO 语句为表创建脚本
【发布时间】:2017-11-29 10:00:06
【问题描述】:

我正在尝试使用 Microsoft.SqlServer.Management.Smo 类获取表的创建脚本。我想得到里面有 GO 语句的脚本。但 SMO 省略了所有 GO 语句和数据库中的 USE。

例如:- 创建从管理工作室生成的脚本。

USE [Testing_BlankData_1_Staging]

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo].[stgUser](
    [UserName] [nvarchar](100) NOT NULL,
    [FullName] [nvarchar](100) NULL,
    [Title] [nvarchar](100) NULL,
    [Department] [nvarchar](100) NULL,
    [Role] [nvarchar](100) NULL
) ON [PRIMARY]

GO

使用 SMO 创建脚本

SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

CREATE TABLE [dbo].[stgUser](
    [UserName] [nvarchar](100) NOT NULL,
    [FullName] [nvarchar](100) NULL,
    [Title] [nvarchar](100) NULL,
    [Department] [nvarchar](100) NULL,
    [Role] [nvarchar](100) NULL
) ON [PRIMARY]

我想要管理工作室的精确副本。请建议..

请找到相同的代码

public void GenerateScript()
{
    string sqlServer = "My SQL Server instance";
    string sqlLogin = "login";
    string sqlPassword = "password"
    string sqlDatabase = "Testing_BlankData_1_Staging";


    Server server = new Server(sqlServer);

    server.ConnectionContext.LoginSecure = true;
    server.ConnectionContext.Login = sqlLogin;
    server.ConnectionContext.Password = sqlPassword;
    server.ConnectionContext.Connect();

    foreach (Table table in server.Databases[sqlDatabase].Tables)
    { 

        StringBuilder sb = new StringBuilder();

        ScriptingOptions options = new ScriptingOptions();
        options.ClusteredIndexes = true;
        options.Default = true;
        options.DriAll = true;
        options.Indexes = true;
        options.IncludeHeaders = true;
        options.AnsiPadding = true;

        StringCollection coll = table.Script(options);

        foreach (string str in coll)
        {
            sb.Append(str);
            sb.Append(Environment.NewLine);
        }

        try

        {
                string path = "Any path " + table.Name + ".sql";
                System.IO.StreamWriter fs = System.IO.File.CreateText(path);
                fs.Write(sb.ToString());
                fs.Close();
        }
        catch (Exception ex)
        {

        }
    }
}

【问题讨论】:

  • 执行这两个语句,您会发现它们实际上是相同的。如果数据库在您的连接字符串中并且 GOs 是隐式的,则无需指定数据库
  • 使用 options.ScriptBatchTerminator = true;但结果还是一样,GO 语句不在查询中。
  • 离题 - 我确信 Google 的 Steve Reed 感谢您将他的照片用于您的个人资料。
  • 您可能希望标记答案以避免被标记为贪吃 - meta.stackoverflow.com/questions/348572/…

标签: c# sql-server database smo


【解决方案1】:

我建议将NoCommandTerminator 设置为false

ScriptingOptions.NoCommandTerminator 属性

如果为真,个人 Transact-SQL 语句在生成的脚本中没有分隔

如果为 False(默认),则单个 Transact-SQL 语句由 使用特定于连接的命令终止符。

还可以考虑将ScriptBatchTerminator 设置为true

【讨论】:

  • @vlabatut 随意写一个新问题。
  • 我只是说@andy.plsql 在评论中给出了原始问题的正确答案。你的答案不正确就是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
  • 2012-06-05
相关资源
最近更新 更多