0

使用 SMO,我遇到了一个很大的性能问题:我编写了所有数据库对象(函数、用户、角色、表......),当我编写除表之外的所有数据库对象时,只需要不到 2 分钟,但是当我启用表脚本时需要2个小时?因此,我使用以下方法加载所有表属性:

   serverSQL.SetDefaultInitFields(typeof(SMO.Table), true);

使 SMO 性能更高,但似乎没有效果。这是我的代码:

public static string dumpTables(SMO.TableCollection tables)
        {
            int cpt = 0;
            SMO.ScriptingOptions scriptingOptions = new SMO.ScriptingOptions();
            StringBuilder sb = new StringBuilder();
            scriptingOptions.IncludeIfNotExists = true;
            scriptingOptions.DriAll = true;
            scriptingOptions.ExtendedProperties = true;  

            foreach (SMO.Table table in tables)
            {
                sb.Append("-- Table " + table.Name + "\n");

                foreach (string scriptline in table.Script(scriptingOptions)) //Script call take a long time
                {
                    sb.Append(scriptline + Environment.NewLine );
                }
                sb.Append("GO" + Environment.NewLine);
                cpt++;
                Console.WriteLine(string.Format("Table {0} : {1}", cpt.ToString(), table.ToString()));
            }
            return sb.ToString();
        }

最后一个问题,对我来说是使用sql脚本直接创建表脚本但是使用SSMS,我可以在几分钟内制作表脚本。(SSMS脚本向导使用SMO还是sql脚本?)谢谢给我一个修复它的问题.

4

2 回答 2

0

我找到了很多解决方法:在为每个 SMO.Table 一个一个地记录所有脚本后,我发现一些脚本花费的时间不到 1 秒,而另一些则需要大约 50 秒!

  1. 因此,第一个解决方法是使用多线程。这样做,让我需要 2 小时才能完成的脚本只需要 20 分钟,速度提高 600%。我尝试使用基本的 ThreadPool,而不是在测试有多少线程允许最佳性能时对其进行优化。以后我会告诉你的。(我将使用不同数量的线程进行测试并记录下来,以查看我的计算机中提高最佳性能的线程数)

  2. 另一种解决方法是在 codeplex 中使用 DBDiff,该源代码允许您在没有 SMO 的情况下更快地编写脚本,但对于那些想要更少代码的人来说没有用(手动编写脚本;-)。您必须使用类来创建sql脚本。但是该工具非常适合同步数据库;-)

于 2012-08-27T19:08:50.993 回答
0

摆脱上面格特·阿诺德的评论,这应该为你做:

public static string dumpTables(SMO.TableCollection tables)
        {
            SMO.ScriptingOptions scriptingOptions = new SMO.ScriptingOptions();
            scriptingOptions.IncludeIfNotExists = true;
            scriptingOptions.DriAll = true;
            scriptingOptions.ExtendedProperties = true;

            SMO.Scripter scripter = new SMO.Scripter();
            scripter.Options = scriptingOptions;

            return scripter.Script(tables);
        }

警告:我不是 C# 程序员(只是 DBA),但 Scripter.Script() 方法可以采用 SqlSmoObject[],这实际上是上面评论中的链接用于提高性能的方法。

于 2012-08-26T21:45:22.893 回答