Quantcast
Channel: SQL Server Database Engine forum
Viewing all articles
Browse latest Browse all 15930

Why does try/catch in SPs ignore DDL/schema errors?

$
0
0

I've wondered about this since I first saw it a while back (I've seen it across numerous SP versions of SQL 2k8R2 so assuming it's not a bug)

If you create a sproc with a transaction and a try/catch block, then something changes the schema of any underlying objects inside your try block, the catch block will never fire and you'll be left with dangling transactions. Why is this?

I never use try/catch myself but have seen this it used needlessly and cause various locking issues

example

CREATE table ##hello (col int)
GO
CREATE proc dbo.tran_test
AS
BEGIN
	begin tran
	begin try
		print 'in try'
		SELECT col FROM ##hello
	end try
	begin catch
		print 'in catch'
		rollback
	end catch
	print 'end'
	commit
	RETURN
END
GO
exec dbo.tran_test
print @@trancount
GO
DROP TABLE ##hello
GO
exec dbo.tran_test
exec dbo.tran_test
exec dbo.tran_test
print @@trancount
==== output
in try
(0 row(s) affected)
end
0
in try
Msg 208, Level 16, State 0, Procedure tran_test, Line 8
Invalid object name '##hello'.
Msg 266, Level 16, State 2, Procedure tran_test, Line 8
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
in try
Msg 208, Level 16, State 0, Procedure tran_test, Line 8
Invalid object name '##hello'.
Msg 266, Level 16, State 2, Procedure tran_test, Line 8
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 2.
in try
Msg 208, Level 16, State 0, Procedure tran_test, Line 8
Invalid object name '##hello'.
Msg 266, Level 16, State 2, Procedure tran_test, Line 8
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 2, current count = 3.
3


Viewing all articles
Browse latest Browse all 15930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>