0

我正在使用 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;
                }
}
}

最后我得到了例外,因为“改变失败表”。即使谷歌搜索也没有帮助..所以我的问题是,使用 C# 做到这一点的最佳方法是什么?

4

1 回答 1

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];
于 2013-02-24T03:02:47.063 回答