【问题标题】:Why doesn't SMO scripter generate foreign key headers?为什么 SMO 脚本程序不生成外键标头?
【发布时间】:2012-10-31 02:59:30
【问题描述】:

我正在创建一个程序来使用随 SQL Server 2008 分发的 SMO 库生成我的数据库架构。

我得到了脚本编写器输出的代码,当它被配置为输出所有内容时,它与 SQL Server Management Studio 输出的代码几乎相同,但有一个奇怪的例外:它不输出它在底部,而 SSMS 有。谁能弄清楚这是为什么?这是我的代码:

private void btnExportScript_Click(object sender, EventArgs ea) {
    Server srv = setupConnection();

    // Reference the database
    if (!srv.Databases.Contains(cbChooseDb.SelectedItem.ToString())) {
        _utils.ShowError("Couldn't find DB '" + cbChooseDb.SelectedItem.ToString() + "'.");
        return;
    }
    Database db = srv.Databases[cbChooseDb.SelectedItem.ToString()];

    StringBuilder builder = new StringBuilder();
    try {
        Scripter scrp = new Scripter(srv);
        scrp.Options.AppendToFile = false;
        scrp.Options.ToFileOnly = false;
        scrp.Options.ScriptDrops = false;             // Don't script DROPs
        scrp.Options.Indexes = true;                  // Include indexes
        scrp.Options.DriAllConstraints = true;        // Include referential constraints in the script
        scrp.Options.Triggers = true;                 // Include triggers
        scrp.Options.FullTextIndexes = true;          // Include full text indexes
        scrp.Options.NonClusteredIndexes = true;      // Include non-clustered indexes
        scrp.Options.NoCollation = false;             // Include collation
        scrp.Options.Bindings = true;                 // Include bindings
        scrp.Options.SchemaQualify = true;            // Include schema qualification, eg. [dbo]
        scrp.Options.IncludeDatabaseContext = false;
        scrp.Options.AnsiPadding = true;
        scrp.Options.FullTextStopLists = true;
        scrp.Options.IncludeIfNotExists = false;
        scrp.Options.ScriptBatchTerminator = true;
        scrp.Options.ExtendedProperties = true;
        scrp.Options.ClusteredIndexes = true;
        scrp.Options.FullTextCatalogs = true;
        scrp.Options.SchemaQualifyForeignKeysReferences = true;
        scrp.Options.XmlIndexes = true;
        scrp.Options.IncludeHeaders = true;

        // Prefectching may speed things up
        scrp.PrefetchObjects = true;

        var urns = new List<Urn>();

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

        // Iterate through the views in database and script each one.  Display the script.
        foreach (Microsoft.SqlServer.Management.Smo.View view in db.Views) {
            if (view.IsSystemObject == false) {
                // View is not a system object, so add it.
                urns.Add(view.Urn);
            }
        }

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

        // Start by manually adding DB context
        builder.AppendLine("USE [" + db.Name + "]");
        builder.AppendLine("GO");

        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.Append(st.Trim(new char[] { '\r', '\n' }) + "\r\nGO\r\n");
        }
    }
    catch (Exception ex) {
        showExceptionError("Couldn't generate script.", ex);
        return;
    }

    try {
        File.WriteAllText(txtExportToFile.Text, builder.ToString());
        _utils.ShowInfo("DB exported to script at: " + txtExportToFile.Text);
    }
    catch (Exception ex) {
        showExceptionError("Couldn't save script file.", ex);
        return;
    }
}

请注意,外键属于 DRI 约束类别,并且由于 scrp.Options.DriAllConstraints = true; 而被编写脚本。

【问题讨论】:

    标签: c# sql-server-2008 tsql smo


    【解决方案1】:

    我有一个解决方案:Can't get EnumScript() to generate constraints

    由于某种原因,Scripter 在给定一个 Urn 列表时不会发出 DRI 约束(外键等),但如果一次给定一个 Urn,它就会发出。诀窍是按照祖先的顺序给 Urns:必须在约束引用它们之前定义表。为此,我使用了DependencyWalker

    这里有一个概要:

            var urns = new List<Urn>();
            Scripter schemaScripter = new Scripter(srv) { Options = schemaOptions };
            Scripter insertScripter = new Scripter(srv) { Options = insertOptions };
            var dw = new DependencyWalker(srv);
    
            foreach (Table t in db.Tables)
                if (t.IsSystemObject == false)
                    urns.Add(t.Urn);
            DependencyTree dTree = dw.DiscoverDependencies(urns.ToArray(), true);
            DependencyCollection dColl = dw.WalkDependencies(dTree);
    
            foreach (var d in dColl)
            {
                foreach (var s in schemaScripter.Script(new Urn[] { d.Urn }))
                    strings.Add(s);
                strings.Add("GO");
                if (scriptData)
                {
                    int n = 0;
                    foreach (var i in insertScripter.EnumScript(new Urn[] {d.Urn}))
                    {
                        strings.Add(i);
                        if ((++n) % 100 == 0)
                            strings.Add("GO");
                    }
                }
            }
    

    注意:每隔一段时间添加一个“GO”可以保持批量较小,这样 SSMS 就不会耗尽内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多