使用事务编写 SQL Server 存储过程的最佳实践 -
- 封闭
TRY..CATCH
块
- 错误检查
@@TRANCOUNT
和ROLLBACK
交易
RAISE
实际ERROR
报警调用程序
样本 -
CREATE PROCEDURE [dbo].[ReAdmissionInsert]
@GRNo varchar(4),
@ClassId numeric(2),
@FacultyId numeric(1),
@Section varchar(1),
@SessionId numeric(1)
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
BEGIN TRAN
insert into ReAdmissionDtl(GRNo,ClassId,FacultyId,Section,SessionId)
values(@GRNo,@ClassId,@FacultyId,@Section,@SessionId)
delete from Discharge where GRNo = @GRNo
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
/*ERROR OCCURED*/
DECLARE @ERROR_MESSAGE NVARCHAR(4000);--MESSAGE TEXT
DECLARE @ERROR_SEVERITY INT;--SEVERITY
DECLARE @ERROR_STATE INT;--STATE
SELECT @ERROR_MESSAGE = ERROR_MESSAGE(),
@ERROR_SEVERITY = ERROR_SEVERITY(),
@ERROR_STATE = ERROR_STATE()
/*RETURN ERROR INFORMATION ABOUT THE ORIGINAL ERROR THAT CAUSED
EXECUTION TO JUMP TO THE CATCH BLOCK.*/
RAISERROR (@ERROR_MESSAGE, @ERROR_SEVERITY, @ERROR_STATE)
END CATCH
END
请注意,@@TRANCOUNT
已检查以验证是否有任何打开的事务和ERROR
消息被保留并引发,因此程序将接收SqlException
.