Sql-Server
儲存過程中的事務
我需要在單個事務中執行 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 ...
語法中,並刪除GO
afterBEGIN 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
語句。您可能需要比這更好的錯誤處理,但如果不了解您的需求,那充其量是困難的。一些很好的閱讀: