2

在 SQL Server 中,我可以创建一个与另一个表重复的表,其中设置了所有约束。我可以在 SQL Server Management Studio 中使用脚本表作为 CREATE TO 来执行此操作。然后我可以在另一个数据库中运行脚本,以便重新创建同一个表但没有数据。我想通过使用 vb.net 代码来做同样的事情。重要的一点是所有约束和表属性都已正确设置。

4

1 回答 1

2

您可以使用 SMO(SQL Server 管理对象)程序集将表脚本化为应用程序内的字符串。我在这里使用 C#,但同样可以在 VB.NET 中轻松完成。

// Define your database and table you want to script out
string dbName = "YourDatabase";
string tableName = "YourTable";

// set up the SMO server objects - I'm using "integrated security" here for simplicity
Server srv = new Server();
srv.ConnectionContext.LoginSecure = true;
srv.ConnectionContext.ServerInstance = "YourSQLServerInstance";

// get the database in question
Database db = new Database();
db = srv.Databases[dbName];

StringBuilder sb = new StringBuilder();

// define the scripting options - what options to include or not
ScriptingOptions options = new ScriptingOptions();
options.ClusteredIndexes = true;
options.Default = true;
options.DriAll = true;
options.Indexes = true;
options.IncludeHeaders = true;

// script out the table's creation 
Table tbl = db.Tables[tableName];

StringCollection coll = tbl.Script(options);

foreach (string str in coll)
{
    sb.Append(str);
    sb.Append(Environment.NewLine);
}

// you can get the string that makes up the CREATE script here
// do with this CREATE script whatever you like!
string createScript = sb.ToString();

您需要引用几个 SMO 程序集。

在此处阅读有关 SMO 以及如何使用它的更多信息:

于 2013-07-20T06:48:06.367 回答