如何使用SMO更改表

时间:2013-02-19 18:25:15

标签: c# sql-server-2008 smo

我正在使用SMO在Sqlserver 2008中动态创建表。现在我想使用SMO为现有表添加新列,但我正在尝试执行代码,最终获得运行时异常为“改为无法表格“。我的代码片段为

 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 failed to table”。但是googled也没有帮助..所以我的问题是,使用C#做到这一点的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

感谢您的帮助..

我解决了它改变了我的数据库连接字符串初始化部分。然后它正常工作..

 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];