如何使用SMO更改表
本文关键字:SMO 何使用 | 更新日期: 2023-09-27 18:00:05
我正在使用SMO在Sqlserver 2008中动态创建表。现在我想使用SMO为现有表添加新列,但我正在尝试执行代码,最终获得运行时异常,如"alter fail-to-table"。我的代码片段为
public static bool Altertable(DynamicTable dynamicTable)
{
if (myDatabase.Tables.Contains(dynamicTable.Name))
{
Table myalterEmpTable = myDatabase.Tables[dynamicTable.Name];
var collist = new List<Column>();
foreach (var item in dynamicTable.Columns)
{
Column col = myalterEmpTable.Columns[item.Name];
if (col == null)
{
Column cols = new Column(myalterEmpTable, item.Name , DataType.UserDefinedDataType(item.Type));
cols.Nullable = item.IsNullable;
cols.Default = "";
collist.Add(cols);
}
}
/*Here I'm getting newly added columns only*/
foreach (var item in collist)
{
myalterEmpTable.Columns.Add(item);
}
try
{
myalterEmpTable.Alter();
}
catch (SmoException ex)
{
throw ex;
}
}
}
最后,我遇到了一个异常,因为"alter fail to table"。即使在谷歌上搜索也无济于事。。所以我的问题是,使用C#做这件事的最佳方法是什么?
感谢您的帮助。。
我解决了它,因为我更改了数据库连接字符串初始化部分。然后它工作正常。。
string connns = ConfigurationManager.AppSettings["conn"];
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connns);
string password = builder.Password;
string userid = builder.UserID;
ServerConnection smoConn = new ServerConnection();
smoConn.ServerInstance = sqlConn.DataSource;
instanceServer = new Server(smoConn);
instanceServer.ConnectionContext.LoginSecure = false;
instanceServer.ConnectionContext.Login = userid;
instanceServer.ConnectionContext.Password = password;
projectDatabase = instanceServer.Databases[sqlConn.Database];