Pages

Wednesday, March 5, 2014

SQL Server Transactions and Error Handling Code and Test Case of Error Handling

-- Example Of SQL Server Transactions and Error Handling
-- and How to Test ErrorHandling Code

-- Create Test Table 
CREATE TABLE TestPritesh(
    ID INT PRIMARY KEY NOT NULL,
    decision NVARCHAR(5),
    CHECK (decision in ('yes','no')) -- Only allowed Yes and No value
);

BEGIN TRAN

DECLARE @ErrorCode INT

INSERT INTO [Test1].[dbo].[TestPritesh]
           ([id]
           ,[decision])
     VALUES
           (4
           ,'yes')


SELECT @ErrorCode = @@ERROR
IF (@ErrorCode <> 0) GOTO PROBLEM

--Check Constraint Error
INSERT INTO [Test1].[dbo].[TestPritesh]
           ([id]
           ,[decision])
     VALUES
           (5
           ,'nono')


SELECT @ErrorCode = @@ERROR
IF (@ErrorCode <> 0) GOTO PROBLEM
    
COMMIT TRAN

PROBLEM:
IF (@ErrorCode <> 0) BEGIN
                PRINT 'Unexpected error occurred!'
                PRINT @ErrorCode
    ROLLBACK TRAN
END

SELECT * FROM [Test1].[dbo].[TestPritesh]


No comments:

Post a Comment