April 19, 2013 at 4:51 am
Good question, and an excellent explanation apart from the point raised by Christian. I don't think the comments are misleading, it is pretty common for a comment to be used simply to label a piece of code (as here) and also pretty common for a comment to say what a piece of code will do if it is executed but not say whether it will be executed or not.
There is one issue with the question, albeit an utterly trivial one: it depends on the setting of IMPLICIT_TRANSACTIONS for the connection. If that's set ON, the rollback includes rolling back the two CREATE statements and the select will return not 1 but an error. Of course the default is OFF, but it would be preferable to mention that the OFF setting is assumed. I'll admit that I would almost certainly have forgotten to mention that myself if I had produced this question, though, and I don't consider leaving it out an omission that in any way spoils the question.
Tom
April 19, 2013 at 4:55 am
L' Eomot Inversé (4/19/2013)
There is one issue with the question, albeit an utterly trivial one: it depends on the setting of IMPLICIT_TRANSACTIONS for the connection. If that's set ON, the rollback includes rolling back the two CREATE statements and the select will return not 1 but an error. Of course the default is OFF, but it would be preferable to mention that the OFF setting is assumed.
Ahh, yes. Good catch, Tom! I should have thought of that when I created the question.
April 19, 2013 at 5:13 am
IgorMi (4/19/2013)
kapil_kk (4/18/2013)
oopes,I think I have misunderstood the way to execute the given query...
After seeing comments First Attempts, second, third I executed one by one those insert query and forget about the GO batch separator... and I was thinking it was so easy question and count will give 3 but i was wrong and lost the points... 🙁
I think most of the think count value as 3 and executed in same fashion that I executed that's why load towards incorrect answer is more than correct answer...
Result of 3 will be given, if GO exists after this insert
-- Insert attempt #2
INSERT INTO dbo.Test (PrimKey, ValueCol)
VALUES (2, -2);
GO
Regards
IgorMi
Thanks Igor 🙂
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
April 19, 2013 at 7:03 am
This was removed by the editor as SPAM
April 19, 2013 at 7:16 am
Another interesting question to finish the week, thanks!
April 19, 2013 at 7:29 am
Good question!
Thanks,
Lon
April 19, 2013 at 7:59 am
Hugo Kornelis (4/19/2013)
Try what happens if you use a CHECK constraint instead of a trigger to prevent negative values.By the way, my questions never intentionally contain "tricks". I try to test knowledge. In this case, I focus on how a rollback from a trigger affects a batch.
I realize, from another posters' comment, that the comments in the code were misleading to some. I am really sorry for that. I absolutely do not want to trick people; I want to test their knowledge (and add to it, of course)
My first thought on seeing this trigger was "Why isn't this a check constraint?" Thanks for mentioning it in these comments.
How does the trigger affect multi-row insert if one fails the trigger condition? How would that scenario be different with CHECK constraint? I know, I should try-it-and-see - but hoped my thinking aloud might turn into another QotD / article [*nudge*] 🙂
fwiw, I didn't feel it was 'tricky' - real code is rarely a trivial case, so if we want to have any hope of solving real problems we should be able to read carefully. (my $0.02)
April 19, 2013 at 8:01 am
Thanks for the excellent question Hugo..
learnt something new..
April 19, 2013 at 8:16 am
Mike Dougherty-384281 (4/19/2013)
How does the trigger affect multi-row insert if one fails the trigger condition? How would that scenario be different with CHECK constraint?
The trigger would roll back the transaction - which is at least the entire statement (all rows), and possible the preceding statements as well if the transaction was started earlier and abort the batch.
The CHECK constraint would roll back the statement (all rows), but leave the transaction intact and continue the batch from the next statement. Of course, error handling code in the batch (or procedure, if one is used) could change that.
April 19, 2013 at 8:33 am
I knew it had to do with the batch but I ended up choosing "0" as in "the whole batch will fail". Stupid me. 😀
Best regards,
Andre Guerreiro Neto
Database Analyst
http://www.softplan.com.br
MCITPx1/MCTSx2/MCSE/MCSA
April 19, 2013 at 8:35 am
Hugo Kornelis (4/19/2013)
Christian Buettner-167247 (4/19/2013)
Hi,There is one subtle issue with the explanation (and also the MS documentation).
It is not the ROLLBACK that is causing the abort of the batch. Instead, the batch is aborted if there is no transaction alive after the end of the trigger (at least that's what I can see from my tests).
For example, adding a BEGIN TRAN right after the ROLLBACK TRAN ensures that the batch is not aborted.
Yes, you are correct. The batch is aborted because no transaction was open when the trigger finished executing. If you change the ROLLBACK in the trigger to COMMIT (though why on earth you'd want to???), the batch still aborts.
More precisely, as you can see from Erland Sommerskag's article that Hugo linked in the explanation, the batch aborts when it exits a trigger context with @@TRANCOUNT = 0. ROLLBACK rolls back everything to the outer transaction, so @@TRANCOUNT = 0 after the ROLLBACK in the trigger executes. As Christian pointed out, a BEGIN TRAN at the end of the trigger will set @@TRANCOUNT = 1 so the batch won't abort.
There is another way to execute a ROLLBACK in a trigger while still exiting the trigger context with @@TRANCOUNT > 0 so that the rest of the batch doesn't about. That is to wrap the whole batch in a transaction, create a savepoint before the statement that fires the trigger and execute a ROLLBACK <savepoint> in the trigger. This is probably a matter of esoteric interest, though, since the need to use the same savepoint name as in the trigger in every bit of code that fires the trigger probably makes it impractical for operational use. This modification of Hugo's code demonstrates that it works, though:
-- NOTE - remove the lower case 'x' from each CREATE and DROP statement - my company blocks internet traffic that includes T-SQL DDL constructs, so I have to stick an extra letter in there to post code samples with DDL.
CxREATE TABLE dbo.Test
(PrimKey int NOT NULL,
ValueCol int NOT NULL,
PRIMARY KEY (PrimKey)
);
go
CxREATE TRIGGER TestTrig
ON dbo.Test
AFTER INSERT
AS
IF EXISTS(SELECT *
FROM inserted
WHERE ValueCol < 0)
BEGIN;
RAISERROR ('Negative values are not allowed!', 16, 1);
ROLLBACK TRAN SAVEPOINT;
END;
go
BEGIN TRANSACTION -- This is the "wrapper" transaction.
-- Insert attempt #1
INSERT INTO dbo.Test (PrimKey, ValueCol)
VALUES (1, 1)
-- Insert attempt #2
SAVE TRANSACTION SAVEPOINT -- The savepoint name must be the same as the name used in the ROLLBACK in the trigger.
INSERT INTO dbo.Test (PrimKey, ValueCol)
VALUES (2, -2)
-- Insert attempt #3
INSERT INTO dbo.Test (PrimKey, ValueCol)
VALUES (3, 3), (4, 4)
COMMIT -- Committing the "wrapper" transaction.
go
-- Predict the output of this query:
SELECT COUNT(*) FROM dbo.Test; -- Note that both Insert attempt #1 and Insert attempt #3 now execute,
-- while Insert #2 is rolled back and the error message returned.
go
DxROP TRIGGER TestTrig;
go
DxROP TABLE dbo.Test;
go
Jason Wolfkill
April 19, 2013 at 10:06 am
Good one; thank you for posting.
(the word "attempt" confused me and I executed one after the other insert statement and as I imagined, it must returned 3, and I was more confused when it pointed as wrong and all the focus was taken by "go"; it would have been great if mentioned "execute the whole as a batch"... might have give more strength to the question)
ww; Raghu
--
The first and the hardest SQL statement I have wrote- "select * from customers" - and I was happy and felt smart.
April 19, 2013 at 10:54 am
Raghavendra Mudugal (4/19/2013)
Good one; thank you for posting.(the word "attempt" confused me and I executed one after the other insert statement and as I imagined, it must returned 3, and I was more confused when it pointed as wrong and all the focus was taken by "go"; it would have been great if mentioned "execute the whole as a batch"... might have give more strength to the question)
"execute the whole as a batch" would be explicitly telling people to remove the batch terminators - ie the go statements - so that the whole could be a batch instead of several batches.
Tom
April 19, 2013 at 11:28 am
L' Eomot Inversé (4/19/2013)
Raghavendra Mudugal (4/19/2013)
Good one; thank you for posting.(the word "attempt" confused me and I executed one after the other insert statement and as I imagined, it must returned 3, and I was more confused when it pointed as wrong and all the focus was taken by "go"; it would have been great if mentioned "execute the whole as a batch"... might have give more strength to the question)
"execute the whole as a batch" would be explicitly telling people to remove the batch terminators - ie the go statements - so that the whole could be a batch instead of several batches.
OH "the sql comments without the word - attempt"
ww; Raghu
--
The first and the hardest SQL statement I have wrote- "select * from customers" - and I was happy and felt smart.
April 19, 2013 at 3:08 pm
Great question!
Thanks!
Rob Schripsema
Propack, Inc.
Viewing 15 posts - 16 through 30 (of 33 total)
You must be logged in to reply to this topic. Login to reply