MSDN 保存事务
CREATE PROCEDURE [dbo].[SaveCustomer]
@Firstname nvarchar(50),
@Lastname nvarchar(50)
AS
DECLARE @ReturnCode int = 1 -- 1 - success
,@NewID int
---------------------------------------------- These variables are for TRY/CATCH RAISEERROR and BEGIN TRAN/SAVE POINT use
,@tranCounter int -- @TranCounter > 0 means an active transaction was started before the procedure was called.
,@errorMessage nvarchar(4000) -- echo error information to the caller. Message text.
,@errorSeverity int -- Severity.
,@errorState int; -- State
SET @tranCounter = @@TRANCOUNT;
IF @tranCounter > 0
SAVE TRANSACTION SaveCustomer_Tran;
ELSE
BEGIN TRANSACTION;
BEGIN TRY
INSERT dbo.Customer (
Firstname
,Lastname)
VALUES (
@Firstname
,@Lastname)
SET @NewID = scope_identity()
IF @tranCounter = 0
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @tranCounter = 0
ROLLBACK TRANSACTION;
ELSE
IF XACT_STATE() <> -1
ROLLBACK TRANSACTION SaveCustomer_Tran;
SELECT @errorMessage = 'Error in [SaveCustomer]: ' + ERROR_MESSAGE(), @errorSeverity = ERROR_SEVERITY(), @errorState = ERROR_STATE();
RAISERROR (@errorMessage, @errorSeverity, @errorState);
SET @ReturnCode = -1
END CATCH
SELECT @ReturnCode as [ReturnCode], @NewID as [NewID]
GO