I'm not sure if @@trancount is on the 70-433 exam but I thought the following was interesting:
http://codebetter.com/blogs/darrell.norton/archive/2003/12/24/4921.aspx
SQL Server Transactions - Commit and Rollback
A coworker was having trouble with a stored proc. There were several IF statements where one path created another nested level transaction while the other did not. Trying to get the stored proc to COMMIT only certain transactions by name was sometimes generating an error that there was no corresponding BEGIN TRANSACTION. What we learned was the following.
Whenever you execute a COMMIT TRANSACTION statement, any transaction name after the statement is ignored. The only thing a COMMIT TRANSACTION statement does is reduce the @@trancount variable by 1. If this makes @@trancount = 0, then all database modifications are committed.
For example, say you have the following code (from SQL Server Books Online):
CREATE TABLE TestTran (Cola INT PRIMARY KEY, Colb CHAR(3))
GO
BEGIN TRANSACTION OuterTran -- @@TRANCOUNT set to 1.
GO
INSERT INTO TestTran VALUES (1, 'aaa')
GO
BEGIN TRANSACTION Inner1 -- @@TRANCOUNT set to 2.
GO
INSERT INTO TestTran VALUES (2, 'bbb')
GO
BEGIN TRANSACTION Inner2 -- @@TRANCOUNT set to 3.
GO
INSERT INTO TestTran VALUES (3, 'ccc')
GO
COMMIT TRANSACTION Inner2 -- Decrements @@TRANCOUNT to 2.
-- Nothing committed.
-- ROLLBACK TRANSACTION Inner1
GO
COMMIT TRANSACTION Inner1 -- Decrements @@TRANCOUNT to 1.
-- Nothing committed.
GO
COMMIT TRANSACTION OuterTran -- Decrements @@TRANCOUNT to 0.
-- Commits outer transaction OuterTran.
GO
DROP TABLE TestTran
No comments:
Post a Comment