【发布时间】:2012-04-17 04:33:19
【问题描述】:
我在我的应用程序中使用 MS Sql 数据库,当我从数据库执行 SELECT 操作时,它会卡住几分钟。 它每天发生几次。所有其他 SELECTS 只需要几秒钟。
我还注意到,如果我在 SELECT 操作正在进行时关闭了应用程序。在我重新启动数据库引擎之前,它在任何下一个应用程序启动时都无法正常工作......
为什么会这样?
这里是sn-p的代码:
using (SqlConnection myConnection = new SqlConnection(connString))
{
myConnection.Open();
SqlCommand command = myConnection.CreateCommand();
SqlTransaction transaction;
transaction = myConnection.BeginTransaction("LockTransaction");
command.Connection = myConnection;
command.Transaction = transaction;
try
{
int recordsAtOnce = maxToLock;
command.CommandText =
"SELECT TOP 1000 id, productName from Parts WHERE part_used is NULL;";
List<string> idList = new List<string>();
SqlDataReader myReader = command.ExecuteReader(CommandBehavior.Default);
while (myReader.Read())
{
string id = myReader.GetString(1);
string name = myReader.GetInt32(0).ToString();
idList.Add(id);
}
myReader.Close();
string idsStr = "";
for(int i = 0; i < idList.Count; i++)
{
if (i != 0)
{
idsStr += ", ";
}
idsStr += idList[i];
}
// lock record
command.CommandText = "UPDATE Parts SET part_used=\'rt\' WHERE id in (" + idsStr + ")";
command.Parameters.Clear();
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
【问题讨论】:
-
您的
Parts表是否在part_used上编入索引?这将避免表扫描。在没有指定ORDER的情况下使用TOP子句是很不寻常的。
标签: c# sql-server select