如何检查事务发生的时间

时间:2014-02-17 21:08:51

标签: sql sql-server tsql

有人知道检查交易发生时的命令吗?

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 个答案:

答案 0 :(得分:1)

您的这种方法是错误的,首先在发生错误时填充@@ERROR函数 如果在发生错误后执行了任何其他语句,则@@ ERROR将设置为null。

要正确使用@@ 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