Sql-Server

儲存過程中的事務

  • May 14, 2020

我需要在單個事務中執行 UPDATE 和 INSERT。該程式碼本身可以正常工作,但我希望能夠輕鬆呼叫它並傳入所需的參數。當我嘗試將此事務嵌套在儲存過程中時,我遇到了很多語法錯誤。

如何封裝以下程式碼以便於呼叫?

BEGIN TRANSACTION AssignUserToTicket
GO

DECLARE @updateAuthor varchar(100)
DECLARE @assignedUser varchar(100)
DECLARE @ticketID bigint

SET @updateAuthor = 'user1'
SET @assignedUser = 'user2'
SET @ticketID = 123456

   UPDATE tblTicket SET ticketAssignedUserSamAccountName = @assignedUser WHERE (ticketID = @ticketID);
   INSERT INTO [dbo].[tblTicketUpdate]
          ([ticketID]
          ,[updateDetail]
          ,[updateDateTime]
          ,[userSamAccountName]
          ,[activity])
    VALUES
          (@ticketID,
          'Assigned ticket to ' + @assignedUser,
          GetDate(),
          @updateAuthor,
          'Assign');
GO
COMMIT TRANSACTION AssignUserToTicket

您需要將該程式碼包裝在CREATE PROCEDURE ...語法中,並刪除GOafterBEGIN TRANSACTION和 before的語句COMMIT TRANSACTION

GO
CREATE PROCEDURE dbo.AssignUserToTicket
(
    @updateAuthor varchar(100)
   , @assignedUser varchar(100)
   , @ticketID bigint
)
AS
BEGIN
   BEGIN TRANSACTION;
   SAVE TRANSACTION MySavePoint;
   SET @updateAuthor = 'user1';
   SET @assignedUser = 'user2';
   SET @ticketID = 123456;

   BEGIN TRY
       UPDATE dbo.tblTicket 
       SET ticketAssignedUserSamAccountName = @assignedUser 
       WHERE (ticketID = @ticketID);

       INSERT INTO [dbo].[tblTicketUpdate]
           (
           [ticketID]
           ,[updateDetail]
           ,[updateDateTime]
           ,[userSamAccountName]
           ,[activity]
           )
       VALUES (
           @ticketID
           , 'Assigned ticket to ' + @assignedUser
           , GetDate()
           , @updateAuthor
           , 'Assign'
           );
       COMMIT TRANSACTION 
   END TRY
   BEGIN CATCH
       IF @@TRANCOUNT > 0
       BEGIN
           ROLLBACK TRANSACTION MySavePoint; -- rollback to MySavePoint
       END
   END CATCH
END;
GO

另請注意,我添加了一個TRY...CATCH語句塊以允許在發生錯誤時執行ROLLBACK TRANSACTION語句。您可能需要比這更好的錯誤處理,但如果不了解您的需求,那充其量是困難的。

一些很好的閱讀:

  1. 始終指定架構
  2. 儲存過程最佳實踐
  3. 要避免的壞習慣

引用自:https://dba.stackexchange.com/questions/134129