SMOを使用してテーブルを自動的に作成するには、ConnectionInfo、Management.Sdk.Sfc、SqlEnumなどの多くの参照を追加する必要があります。NugetでSMOを直接検索して、Unofficial.Microsoft.SQLServerを見つけることができます。 SMO.2014は、Nils Luckによって提供されていますが、今回必要なすべての参照がすでに含まれています。
ここでの情報に基づいて自動テーブル作成を完全に実現します。実際のニーズに応じて変更できるコードで直接デモンストレーションします。主にDictionary <string、Dictionary <string、string >>を使用してテーブル情報を転送します。もちろん、実際の状況は、実際のニーズに応じて変更されます。
static void Main(string[] args)
{
try
{
//利用Dictionary进行表信息传递,string传递列名,另一个Dictionary中包含类型和大小
Dictionary<string,Dictionary<string,string>> columnInfo = new Dictionary<string,Dictionary<string,string>>();
Dictionary<string,string> typeAndSize1 = new Dictionary<string,string>();
typeAndSize1.Add("INT","0");
columnInfo.Add("NUMBER",typeAndSize1);
Dictionary<string,string> typeAndSize2 = new Dictionary<string,string>();
typeAndSize2.Add("DATETIME","0");
columnInfo.Add("NAME",typeAndSize2);
bool isSuccess = AutoCreateDataTable("XX.XXX.XX.XXX","DATABASE","TABLETEST",columnInfo);
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
//自动创建数据表
private static bool AutoCreateDataTable(string dataSource,string dataBaseName,string tableName,Dictionary<string,Dictionary<string,string>> columnInfo)
{
bool isSuccess = false;
try
{
//连接数据库拼接
string connectionString = "Data Source = " + dataSource + ";Initial Catalog = " + dataBaseName + ";Integrated Security = SSPI;";
SqlConnection cn = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(cn));
//数据库
DataBase db = server.Database[dataBaseName];
//建表
Table newTable = new Table(db,tableName);
//ID列信息
Column idColumn = new Column(newTable,"ID");
//类类型
idColumn.DataType = DataType.Int;
//是否null
idColumn.Nulllable = false;
//是否自增
idColumn.Identity = true;
//起始大小
idColumn.IdentitySeed = 1;
//步长
idColumn.IdentityIncrement = 1;
//将列放入table中
newTable.Columns.Add(idColumn);
//索引
Index.index = new Index(newTable,"PK_ID");
Index.IndexKeyType = IndexKeyType.DriprimaryKey;
index.IndexedColumns.Add(new IndexedColumn(index,"ID"));
newTable.Indexes.Add(index);
//遍历Dictionary获取表信息
foreach(string key in columnInfo.Keys)
{
Column column = new Column(newTable,key);
column.DataType = GetDataType(columnInfo[Key]);
newTable.Columns.Add(column);
}
newTable.Create();
isSuccess = true;
}
catch(Exception ex)
{
isSuccess = false;
Console.WriteLine(ex);
}
return isSuccess;
}
private static DataType GetDataType(Dictionary<string,string> typeAndSize)
{
foreach(string s in typeAndSize.Keys)
{
switch(s.ToString())
{
case "VARCHAR":
if("MAX".Equals(typeAndSize[s]))
{
return DataType.VarCharMax;
}
else
{
return DataType.VarChar(int.Parse(typeAndSize[s]));
}
case "INT":
return DataType.Int;
case "FLOAT":
return DataType.Float;
//类型太多,根据自己实际需要进行添加
}
}
}