我在我的應用程序中使用MS Sql數據庫,當我從數據庫執行SELECT操作時,它會搜索幾分鐘。 它每天發生幾次。所有其他SELECTS只需幾秒鐘。數據庫卡在SELECT操作
另外我注意到,如果我在SELECT操作正在進行時關閉應用程序。直到我重新啓動數據庫引擎時,它根本無法工作...
爲什麼會這樣?
這裏是代碼片段:
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();
}
'part_used'是你的'Parts'表的索引嗎?這將避免表掃描。在不指定ORDER的情況下,有一個「TOP」子句是不尋常的。 – HABO 2012-04-03 15:17:09