Csharp/C#教程:使用SMO获取表默认值的创建传奇脚本共享


使用SMO获取表默认值的创建脚本

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

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

对于索引,它就像

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属性。 是否有其他方法为表默认值生成脚本?

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

 Server server = new Server(@".SQLEXPRESS"); Database db = server.Databases["AdventureWorks"]; List list = new List(); 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()); 

虽然我没有使用SMO,但我查找了MSDN,这是我发现的。

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

这是你想要的?

除了帕维尔的答案。

我只需要为一个invidual表获取脚本。 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 + ";"); } 

我希望它能帮助未来的读者。

上述就是C#学习教程:使用SMO获取表默认值的创建脚本分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/987760.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐