0

ADO.NET を使用して CREATE TABLE スクリプトを生成し、特定のテーブルの正確なコピーを作成したいと考えています。

この理由は、持続性テストです。アプリケーションが特定のデータベースに永続化されるかどうかを知りたいです。アプリが問題のデータベースとテーブルを指すようにしたいと思います。アプリは、指定されたテーブルの正確なコピーを使用して新しいデータベースを生成します。したがって、元のデータベースに触れることなく、複製されたテーブルに対して永続性テストを実行できます。完了したら、新しいデータベースを簡単に削除できます。

この野心的なプロジェクトに着手する前に、何か既に存在するかどうかを知りたい. Google を試してみましたが、コードではなく SSMS UI を介してスキーマ生成 SQL を取得する方法しか見つかりませんでした。

4

1 に答える 1

3

これにはSQL管理オブジェクト(SMO)を使用できます。

例(C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SqlServer.Management.Smo;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Server srv = new Server(@".\SQLEXPRESS");
            Database db = srv.Databases["MyDB"];

            Scripter scrp = new Scripter(srv);
            scrp.Options.ScriptDrops = false;
            scrp.Options.WithDependencies = true;

            //Iterate through the tables in database and script each one. Display the script. 
            //Note that the StringCollection type needs the System.Collections.Specialized namespace to be included. 
            Microsoft.SqlServer.Management.Sdk.Sfc.Urn[] smoObjects = new Microsoft.SqlServer.Management.Sdk.Sfc.Urn[1];
            foreach (Table tb in db.Tables)
            {
                smoObjects[0] = tb.Urn;
                if (tb.IsSystemObject == false)
                {
                    System.Collections.Specialized.StringCollection sc;
                    sc = scrp.Script(smoObjects);
                    foreach (string st in sc)
                        Console.WriteLine(st);
                }
            }
            Console.ReadKey();
        }
    }
}
于 2010-09-03T11:07:06.173 に答える