【问题标题】:Using SMO to get create script for table defaults使用 SMO 获取表默认值的创建脚本
【发布时间】:2008-11-08 05:33:51
【问题描述】:

我正在尝试为我正在使用的本地数据库创建数据库脚本工具。

我已经能够为表、主键、索引和外键生成创建脚本,但是我找不到任何方法来为表默认值生成创建脚本。

对于索引,就这么简单

foreach (Index index in table.Indexes)
{
    ScriptingOptions drop = new ScriptingOptions();
    drop.ScriptDrops = true;
    drop.IncludeIfNotExists = true;

    foreach (string dropstring in index.Script(drop))
    {
        createScript.Append(dropstring);
    }

    ScriptingOptions create = new ScriptingOptions();
    create.IncludeIfNotExists = true;

    foreach (string createstring in index.Script(create))
    {
        createScript.Append(createstring);
    }
}

但是 Table 对象没有 Defaults 属性。是否有其他方法可以为表默认值生成脚本?

【问题讨论】:

    标签: c# sql-server smo


    【解决方案1】:

    尝试使用带有 DriAll 选项集的 Scripter 对象:

    Server server = new Server(@".\SQLEXPRESS");
    Database db = server.Databases["AdventureWorks"];
    List<Urn> list = new List<Urn>();
    DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table);
    foreach (DataRow row in dataTable.Rows)
    {
       list.Add(new Urn((string)row["Urn"]));
    }
    Scripter scripter = new Scripter();
    scripter.Server = server;
    scripter.Options.IncludeHeaders = true;
    scripter.Options.SchemaQualify = true;
    scripter.Options.SchemaQualifyForeignKeysReferences = true;
    scripter.Options.NoCollation = true;
    scripter.Options.DriAllConstraints = true;
    scripter.Options.DriAll = true;
    scripter.Options.DriAllKeys = true;
    scripter.Options.DriIndexes = true;
    scripter.Options.ClusteredIndexes = true;
    scripter.Options.NonClusteredIndexes = true;
    scripter.Options.ToFileOnly = true;
    scripter.Options.FileName = @"C:\tables.sql";
    scripter.Script(list.ToArray());
    

    【讨论】:

    • 嗨 Pavel,如果我只想为表格生成脚本。例如说:Production.Categories。我必须添加什么脚本?谢谢
    • @Goldfish 你能问一个单独的问题吗?您可以在此处链接此答案。
    【解决方案2】:

    虽然我没有使用过 SMO,但我查阅了 MSDN,找到了以下内容。

    Table 有一个 Columns 属性(列集合),它应该引用每一列。
    每个 Column 都有一个 DefaultConstraint 属性。

    这是你要找的吗?

    【讨论】:

      【解决方案3】:

      Pavel 的答案。

      我只需要获取单个表格的脚本。 1. 我想将表模式名和表名作为参数传递并生成脚本。 2. 将脚本分配给变量而不是写入文件。

      单个表的代码:

      /*get a particular table script only*/
      Table myTable = db.Tables["TableName", "SchemaName"];
      scripter.Script(new Urn[] { myTable.Urn});
      

      将脚本写入变量:

      StringCollection sc = scripter.Script(new Urn[] { myTable.Urn });
      foreach (string script in sc)
      {
          sb.AppendLine();
          sb.AppendLine("--create table");
          sb.Append(script + ";");
      }
      

      希望对以后的读者有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-06
        • 1970-01-01
        • 2010-12-16
        • 2016-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多