Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Robowski
Posting Yak Master
101 Posts |
Posted - 2013-11-14 : 06:26:02
|
Just started using try/catch and hit a problem.Tried simplifying it and would expect the below to print '1 = 1' but it isn't.BEGIN TRYBEGIN TRAN PRINT '1 = 2' COMMIT TRANEND TRYBEGIN CATCH IF 1 = 1 BEGIN PRINT '1 = 1' END; IF 1 = 1 ROLLBACK TRANTHROW;END CATCH |
|
vijays3
Constraint Violating Yak Guru
354 Posts |
Posted - 2013-11-14 : 06:32:48
|
There is no error in Try block so it wont move into catch blockeverything is fine in try block so it is printing 1 = 2BEGIN TRYBEGIN TRAN--PRINT '1 = 2'select 1/0COMMIT TRANEND TRYBEGIN CATCHIF 1 = 1 BEGINPRINT '1 = 1'END;--IF 1 = 1 ROLLBACK TRAN--THROW;END CATCHVijay is here to learn something from you guys. |
 |
|
Robowski
Posting Yak Master
101 Posts |
Posted - 2013-11-14 : 06:38:02
|
I see, so you can't use the begin catch block to create custom errors?For example, if more than two rows are inserted throw and error?Would have to revert to a using raiserror within a transaction instead?quote: Originally posted by vijays3 There is no error in Try block so it wont move into catch blockeverything is fine in try block so it is printing 1 = 2BEGIN TRYBEGIN TRAN--PRINT '1 = 2'select 1/0COMMIT TRANEND TRYBEGIN CATCHIF 1 = 1 BEGINPRINT '1 = 1'END;--IF 1 = 1 ROLLBACK TRAN--THROW;END CATCHVijay is here to learn something from you guys.
|
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-11-14 : 07:32:25
|
quote: Originally posted by Robowski I see, so you can't use the begin catch block to create custom errors?For example, if more than two rows are inserted throw and error?Would have to revert to a using raiserror within a transaction instead?quote: Originally posted by vijays3 There is no error in Try block so it wont move into catch blockeverything is fine in try block so it is printing 1 = 2BEGIN TRYBEGIN TRAN--PRINT '1 = 2'select 1/0COMMIT TRANEND TRYBEGIN CATCHIF 1 = 1 BEGINPRINT '1 = 1'END;--IF 1 = 1 ROLLBACK TRAN--THROW;END CATCHVijay is here to learn something from you guys.
yep. you need to use RAISERROR for that. Or if in SQL 2012 or later use THROW------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
 |
|
|
|
|