2014-02-17 37 views
0

有谁知道检查交易何时发生的命令?如何检查交易何时发生

BEGIN TRAN 
BEGIN 
    --- Do stuff with @id 
    INSERT INTO tbl_1(id, col_1, col_2) 
    SELECT @id, @val_1, val_2, 
    .. 
    ..... 
    ......... 
END 
IF (@@ERROR <> 0) 
BEGIN 
    ROLLBACK TRAN 
END ELSE 
BEGIN 
    COMMIT TRAN --> would like to know when this started or logged? 

     -- Thinking about adding "exe some_trans_log getDate(), 'start - web_sp @id'" here 

      EXEC web_sp @id --> this takes a while to execute 

     -- Thinking about adding exe some_trans_log getDate(), 'end - web_sp @id' 

END 

我不认为有必要在您的交易中添加日志记录,但我可能是错的。

回答

1

你的这种做法是错误的,首先@@ERROR函数一旦发生错误就会填充 ,并且在错误发生后有任何其他语句被执行后@@ ERROR被设置为空。

要正确使用@@ ERROR函数,只要您执行语句,就必须将其值存储到变量中。但是,要预测哪里出现错误,并将其值存储到变量中,那就太过于简单了。错误可能会发生在你没有反应的地方。

我们在SQL Server中有TRY..CATCH块,这使得这种执行非常简单。

您在try块中执行您的主代码,并在代码执行过程中,如果出现错误,控件跳转到catch块,那么您有Sql Server Error Functions来收集关于错误的详细信息。

我会用下面的办法来写代码是这样的....

BEGIN TRY 

    /* Do some obvious validation checks here */ 

    -- Check 1 
     IF(Something is not true) 
     BEGIN 
      RAISERROR('Something has gone wrong', 16,1) 
     END 

    -- Check 2 
     IF(Something is not true) 
     BEGIN 
      RAISERROR('Something has gone wrong', 16,1) 
     END 
/* once you have done your checks then open a transations*/ 

    BEGIN TRANSACTION 

     INSERT INTO tbl_1(id, col_1, col_2) 
     SELECT @id, @val_1, val_2, 


    COMMIT TRANSACTION 
END TRY 

BEGIN CATCH 

/* If the validation failed and an error was raised 
control will jump to this catch block Transaction was 
never BEGAN. 

if all the validations passed and something went wrong 
    when transaction was open. then it will roll back the 
    open transaction. 
*/ 
IF @@TRANCOUNT <> 0 
BEGIN 
    ROLLBACK TRANSACTION 
END 

    SELECT ERROR_LINE() AS [Error_Line], 
      ERROR_MESSAGE AS [ERROR_MESSAGE], 
      ERROR_NUMBER AS [ERROR_NUMBER] 

/* Use Error Function to collect information about the error */ 

/* Do other stuff log information about error bla bla */ 

END CATCH