【发布时间】:2013-02-21 15:28:53
【问题描述】:
我正在向数据库中插入大量行并尝试在其上建立主键。如果我立即创建表并建立一个键,即使使用 SQLBulkCopy 命令,插入数据的时间也会增加 10 倍。所以这不是一个可行的选择。我现在要做的是插入数据,全部插入后,使用 SMO 创建主键。问题是,即使连接字符串中的超时设置为 0,我仍然在 alter() 命令上收到超时异常。关于如何解决这个问题的任何想法?
connectionString.ConnectTimeout = 0;
ServerConnection scon = null;
using (SqlConnection conn = new SqlConnection(connectionString.ConnectionString))
{
conn.Open();
try
{
scon = new ServerConnection(conn);
Console.WriteLine("Server Connection Timeout: " + scon.ConnectTimeout);
Server serv = new Server(scon);
Database db = serv.Databases[connectionString.InitialCatalog];
Table table = db.Tables[tableName];
Index i = new Index(table, "pk_" + table.Name);
i.IndexKeyType = IndexKeyType.DriPrimaryKey;
foreach (String s in PrimaryKey)
{
i.IndexedColumns.Add(new IndexedColumn(i, s.Trim()));
}
table.Indexes.Add(i);
table.Alter();
scon.Disconnect();
}
finally
{
conn.Close();
}
}
【问题讨论】:
-
是否需要使用 SMO?
-
@MichaelPerrenoud 对于干净和一致的代码,我想。您是否只想创建一个 SQL 脚本并运行它?
-
你不需要conn.close(),你已经将连接封装在一个Using语句中,连接会自动关闭。
-
@Derek 我知道这一点,现在我只是想在 table.Alter();
-
scon = new ServerConnection(conn); scon.ConnectionContext.StatementTimeout = 0;阅读这个,它可能会有所帮助:- stackoverflow.com/questions/10511984/how-to-set-commandtimeout
标签: c# primary-key smo