2012-02-28 42 views
0

我有一个调用web服务的ASP .net应用程序。 Web服务调用数据访问类来更新数据库。使用ASP的SQL服务器事务的工作.net

我有我的web服务代码段(实际上是一个伪代码)类似以下内容:

Public Function SubmitCheque(//params are passed here) 
    //Call sql stored procedure(SP1) to generate a reference Number 

    //Begin loop. loop count would be number of records that are in a collection 
     //Insert records to database using another stored procedure(SP2) using the 
     //reference number generated in the previous step 
    //End Loop 
End Function 

SP1执行一个表上的select查询,获取最后一行的列值,然后通过增加其序列1.说,如果最后一行的值是ABC02282012 * *,那么我的新的基准数将ABC02282012 * *

SP2执行单个插入语句,而且它插入将有参考行生成的编号。

这是预计会发生的问题,我不确定正确的方法。

在我的代码中,SP1和SP2按顺序执行,并且在SP1和SP2之间的时间间隔以毫秒为单位,应用程序的另一个实例可能会执行SP1并可以获得相同的事务编号。所以有可能多个用户同时访问应用程序可能最终会得到相同的交易编号,这是一个大问题。

我想知道这是否是SQL服务器会照顾或做的事情我需要以不同的方式重写存储过程或代码来实现事务。

请帮助并让我知道您的意见。

回答

2

你会更好地实现单个存储过程中的所有逻辑,并将语句包装在合适的事务中。

如果未能使用TransactionScope在事务中引入单独的操作。例如:

try 
{ 
    // Create the TransactionScope to execute the commands, guaranteeing 
    // that both commands can commit or roll back as a single unit of work. 
    using (TransactionScope scope = new TransactionScope()) 
    { 
     using (SqlConnection connection1 = new SqlConnection(connectString1)) 
     { 
      // Opening the connection automatically enlists it in the 
      // TransactionScope as a lightweight transaction. 
      connection1.Open(); 


      // Call sql stored procedure(SP1) to generate a reference Number     

      SqlCommand command1 = new SqlCommand(commandText1, connection1); 
      returnValue = command1.ExecuteScalar(); 


      //Begin loop. loop count would be number of records that are in a collection 
       //Insert records to database using another stored procedure(SP2) using the 
       //reference number generated in the previous step 
      //End Loop 

     } 
     // The Complete method commits the transaction. If an exception has been thrown, 
     // Complete is not called and the transaction is rolled back. 
     scope.Complete(); 
    } 
} 
catch (TransactionAbortedException ex) 
{ 
    writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message); 
} 
+0

我明白,但有一个.net收集,其中包含几个付款指示(例如说4次付款和计数甚至可以是10)。如果我将这些参数作为参数传递给我的存储过程,那么我的存储过程输入参数可能看起来太冗长。 – SARAVAN 2012-02-28 08:55:56

+0

我正在查看TransactionScope。如果我在一个TransactionScope中打包SP调用,它会被视为单个事务吗? – SARAVAN 2012-02-28 09:08:18

+0

感谢您的示例代码片段。一个区别是,我没有打开任何SQL连接的功能。它只有打开SQL连接的其他类库函数(从我的服务中调用)。 \ n在使用事务范围时,这种情况是否仍被视为事务。 – SARAVAN 2012-02-28 09:13:52