使用vb.net将脚本表作为CREATE TO

时间:2013-07-20 06:28:36

标签: sql sql-server vb.net

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

1 个答案:

答案 0 :(得分: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以及如何在此处使用它: