利用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;
//类型太多,根据自己实际需要进行添加
}
}
}