试图在C#代码中使两个SQL INSERT语句成为原子

时间:2012-08-16 04:35:12

标签: c# sql transactions ssis atomic

以下是我在SSIS脚本任务中使用的代码。我试图使两个插入原子,因为他们处理类似的客户。

第一个.executeNonQuery()工作正常,按原样锁定SQL表。

第二个.executNonQuery()会抛出错误:

  

ExecuteNonQuery需要命令才能拥有事务   分配给该命令的连接位于挂起的本地事务中。   该命令的Transaction属性尚未初始化。

代码:

    ConnectionManager cm; 
    SqlTransaction sqlTrans;
    SqlConnection sqlConn;
    SqlCommand sqlComm;                                  
    cm = Dts.Connections["connectionManager"];

    try
    {
         //Set 'global' variables                                        
         SqlParameter agentID = new SqlParameter("@agentID", 1000018); //retrievedMessage.Substring(2, 10));//Primary key
         SqlParameter lastChangeOperator = new SqlParameter("@lastChangeOperator", "LVO");
         SqlParameter lastChangeDate = new SqlParameter("@lastChangeDate", DateTime.Now);
         SqlParameter controlId = new SqlParameter("@controlID", 1); //Hard-coded value for testing - CHANGE LATER

         //Set variables for Agent table
         SqlParameter entityType = new SqlParameter("@entityType", "P");//retrievedMessage.Substring(162, 1));
         SqlParameter fName = new SqlParameter("@fName", "test");//retrievedMessage.Substring(12, 25));
         SqlParameter lName = new SqlParameter("@lName", "test");//retrievedMessage.Substring(37, 35));
         SqlParameter suffix = new SqlParameter("@suffix", "test");//retrievedMessage.Substring(72, 10));
         SqlParameter corporateName = new SqlParameter("@corporateName", "Initech");//retrievedMessage.Substring(82, 80));

         //Insert record into Agent table
         sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);
         sqlComm = new SqlCommand
         (
           "SET IDENTITY_INSERT Agent ON " +
           "INSERT INTO Agent (UniqueAgentId, EntityType, FirstName, LastName, NameSuffix, CorporateName, LastChangeOperator, LastChangeDate, ControlId) " +
           "VALUES (@agentID, @entityType, @fName, @lName, @suffix, @corporateName, @lastChangeOperator, @lastChangeDate, @controlID)" +
           "SET IDENTITY_INSERT Agent OFF",
            sqlConn//, sqlTrans
         );

         sqlTrans = sqlConn.BeginTransaction("SqlAgentTableUpdates");
         sqlComm.Parameters.Add(agentID);
         sqlComm.Parameters.Add(lastChangeOperator);
         sqlComm.Parameters.Add(lastChangeDate);
         sqlComm.Parameters.Add(controlId);
         sqlComm.Parameters.Add(entityType);
         sqlComm.Parameters.Add(fName);
         sqlComm.Parameters.Add(lName);
         sqlComm.Parameters.Add(suffix);
         sqlComm.Parameters.Add(corporateName);
         sqlComm.Transaction = sqlTrans;
         sqlComm.ExecuteNonQuery();

         //Set variables for AgentIdentification table
         SqlParameter taxIdType = new SqlParameter("taxIdType", "S");//Hard-coded value for testing - CHANGE LATER
         SqlParameter agentTaxId = new SqlParameter("@agentTaxId", "999999999");//Hard-coded value for testing - CHANGE LATER

         //Insert record into AgentIdentification table
         sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);
         sqlComm = new SqlCommand
         (
           "INSERT INTO AgentIdentification (UniqueAgentId, TaxIdType, AgentTaxId, LastChangeOperator, LastChangeDate, ControlId) " +
           "VALUES (@agentID, @taxIdType, @agentTaxId, @lastChangeOperator, @lastChangeDate, @controlId)",
            sqlConn//, sqlTrans
         );

         sqlComm.Parameters.Add(taxIdType);
         sqlComm.Parameters.Add(agentTaxId);
         sqlComm.Transaction = sqlTrans;
         sqlComm.ExecuteNonQuery();
    }
    catch (Exception)
    {
       sqlTrans.Rollback();
       cm.ReleaseConnection(sqlConn);
    }
    finally
    {
       sqlTrans.Commit();
       cm.ReleaseConnection(sqlConn);
    }

修改

我能够通过消除第二个连接来使这个事务工作。但是,两个查询都使用几个相同的变量(SqlParameters)。我被迫复制这些,以便运行没有错误。有没有办法让他们分享变量,所以我不必浪费空间重新创建它们?

3 个答案:

答案 0 :(得分:0)

事务不能跨越多个连接... cm.AcquireConnection每次都返回一个新连接吗?如果是这样,请尝试对两个命令使用相同的连接。

答案 1 :(得分:0)

使用transactionscope

using(TransactionScope ts = new TransactionScope())
{

        using(SqlConnection conn = new SqlConnection(myconnstring)
        {
            conn.Open();
    //call first executenonquery
    //call second executenonquery
            ts.Complete();
            conn.Close();
        }
}

答案 2 :(得分:0)

我认为问题可能出在连接上,或者当您将命令设置为第二个插入的新命令时,您可以使用具有相同连接的两个不同命令,或者只使用一个命令来更改CommandText属性。

希望这有助于...... Using SqlTransaction