SQL Server Management Studio ではCREATE TABLE
、テーブルを右クリックして [.] を選択することで、テーブルのスクリプトを生成できますScript Table As
。
C#でこれと同じ結果を得るにはどうすればよいですか? SMO やその他の方法論を利用できますか?
[質問がクローズされるのを避けるために、ワンライナーや高レベルのドキュメントへのリンクではなく、実際のコード サンプルを投稿してください。]
SQL Server Management Studio ではCREATE TABLE
、テーブルを右クリックして [.] を選択することで、テーブルのスクリプトを生成できますScript Table As
。
C#でこれと同じ結果を得るにはどうすればよいですか? SMO やその他の方法論を利用できますか?
[質問がクローズされるのを避けるために、ワンライナーや高レベルのドキュメントへのリンクではなく、実際のコード サンプルを投稿してください。]
次のコードは、サーバー「XXX」、テーブル「ZZZ」、スキーマ「PPP」を指定して、場所「QQQ」にスクリプトを作成します。データベース全体のコピーを実行するためのスクリプトの例がいくつかあります。これはテーブルのみを対象としています。これは私がこれまでずっと理解しようとしていたことであり、私は最終的に以下のコードを使用してそれを機能させることができました。これは単純な例であることが意図されています。たとえば、結果のスクリプトはテーブルのインデックスを作成せず、最も基本的な構造を作成します。スクリプトの作成方法を指定するには、ScriptingOptionsのインスタンスをtable.Script()の呼び出しに渡します。
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.SqlEnum;
using System.Configuration;
using System.Collections.Specialized;
namespace SmoTest {
class Program {
static void Main(string[] args) {
Server server = new Server("XXX");
Database database = new Database();
database = server.Databases["YYY"];
Table table = database.Tables["ZZZ", @"PPP"];
StringCollection result = table.Script();
var script = "";
foreach (var line in result) {
script += line;
}
System.IO.StreamWriter fs = System.IO.File.CreateText(@"QQQ");
fs.Write(script);
fs.Close();
}
}
}
もう少し完全な例を次に示します (私の友人 Ben Miller から盗みました):
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.SqlEnum;
using Microsoft.SqlServer.Management.Smo.CoreEnum;
using System.Configuration;
using System.Collections.Specialized;
namespace SmoTest
{
class Program
{
static void Main(string[] args)
{
Server srv = new Server();
// really you would get these from config or elsewhere:
srv.ConnectionContext.Login = "foo";
srv.ConnectionContext.Password = "bar";
srv.ConnectionContext.ServerInstance = "ServerName";
string dbName = "DatabaseName";
Database db = new Database();
db = srv.Databases[dbName];
StringBuilder sb = new StringBuilder();
foreach(Table tbl in db.Tables)
{
ScriptingOptions options = new ScriptingOptions();
options.ClusteredIndexes = true;
options.Default = true;
options.DriAll = true;
options.Indexes = true;
options.IncludeHeaders = true;
StringCollection coll = tbl.Script(options);
foreach (string str in coll)
{
sb.Append(str);
sb.Append(Environment.NewLine);
}
}
System.IO.StreamWriter fs = System.IO.File.CreateText("c:\\temp\\output.txt");
fs.Write(sb.ToString());
fs.Close();
}
}
}