修改如下
我有加入qlTransaction sqlTran = conn.BeginTransaction(); // 開始事務
但執行時卻出現
Error:當指定給命令的連接為擱置的本機交易時,ExecuteNonQuery 需要連接以交易。命令的 Transaction 屬性尚未初始化。
請問,這一段是否因為多個ExecuteNonQuery ?
要如何解決呢?
謝謝
using (SqlConnection conn = new SqlConnection(_Conn))
{
using (SqlCommand command = new SqlCommand("", conn))
{
command.CommandTimeout = 300;
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction(); // 開始事務
//------------1.Create temp table
command.CommandText = @"CREATE TABLE #TempAA
(
[holiday] varchar (8) NULL,
[workno] varchar (6) NOT NULL,
)";
command.ExecuteNonQuery();
//------------2. Bulk copy data into temp table
using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
sqlBC.DestinationTableName = "#TempAA";
sqlBC.ColumnMappings.Add("holiday", "holiday");
sqlBC.ColumnMappings.Add("workno", "workno");
sqlBC.WriteToServer(dt);
}
// 3. Join updating table with temp table and run update
// 4. Delete updated records from temp table
// 5.Insert what is left in temp table
command.CommandText = @" DELETE m
FROM holiday2 m
WHERE;
INSERT INTO hr_holiday2
SELECT * FROM #tempAA;
DROP TABLE #TempAA;
";
command.ExecuteNonQuery();
try
{
// sqlBC.WriteToServer(dt);
sqlTran.Commit();
js = "OK";
}
catch (Exception)
{
js = "ERR";
sqlTran.Rollback();
throw;
}
finally
{
//sqlBC.Close();
// conn.Close();
}
//開始寫入
} //---using (SqlCommand command
} //----USING CONN
在執行ExecuteNonQuery之前,Command也要知道是Transaction
在執行命令前要加入這行
command.Transaction = sqlTran;