使用 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 属性。 还有其他方法可以为表默认值生成脚本吗?
I'm trying to create a database scripter tool for a local database I'm using.
I've been able to generate create scripts for the tables, primary keys, indexes, and foreign keys, but I can't find any way to generate create scripts for the table defaults.
For indexes, it's as easy as
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);
}
}
But the Table object doesn't have a Defaults property. Is there some other way to generate scripts for the table defaults?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 设置了 DriAll 选项的 Scripter 对象:
Try using Scripter object with DriAll option set:
虽然我没有使用过 SMO,但我查阅了 MSDN,这是我发现的。
表有一个 Columns 属性(列集合),它应该引用每一列。
每个列都有一个 DefaultConstraint 属性。
这是你想要的?
While I haven't used SMO, I looked up MSDN and here is what I found.
Table has a Columns property (column collection), which should have reference to each column.
Each Column will have a DefaultConstraint property.
Is this what you are looking for?
除了帕维尔的答案。
我只需要获取单个表的脚本。 1.我想将表模式名称和表名称作为参数传递并生成脚本。 2. 将脚本分配给变量而不是写入文件。
单个表的代码:
将脚本写入变量:
我希望它会对未来的读者有所帮助。
Addition to the Pavel's answer.
I needed to get the script for a invidual table only. 1. I wanted to pass the table schema name and table name as parameter and generate script. 2. assign the script to a variable rather than writing to file.
code for a individual table:
Write script to a variable:
I hope it will help future readers.