-- 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]
Pages
▼
No comments:
Post a Comment