2

SQLサーバーでは、すべての制約が設定された別のテーブルの複製であるテーブルを作成できます。これを行うには、SQL サーバー管理スタジオでスクリプト テーブルを CREATE TO として使用できます。次に、別のデータベースでスクリプトを実行して、同じテーブルが再作成されますが、データはありません。vb.net コードを使用して同じことをしたいです。重要な点は、すべての制約とテーブル プロパティが適切に設定されていることです。

4

1 に答える 1

2

SMO (SQL Server Management Objects) アセンブリを使用して、アプリケーション内でテーブルを文字列にスクリプト化できます。ここでは 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 に答える