SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Triggers 1


Triggers 1

Author
Message
Lon-860191
Lon-860191
SSCommitted
SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)SSCommitted (2K reputation)

Group: General Forum Members
Points: 1989 Visits: 278
Good question!
Thanks,
Lon
Mike Dougherty-384281
Mike Dougherty-384281
SSC Eights!
SSC Eights! (852 reputation)SSC Eights! (852 reputation)SSC Eights! (852 reputation)SSC Eights! (852 reputation)SSC Eights! (852 reputation)SSC Eights! (852 reputation)SSC Eights! (852 reputation)SSC Eights! (852 reputation)

Group: General Forum Members
Points: 852 Visits: 944
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*] Smile

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)
pchirags
pchirags
SSCrazy
SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)

Group: General Forum Members
Points: 2717 Visits: 616
Thanks for the excellent question Hugo..
learnt something new..
Hugo Kornelis
Hugo Kornelis
SSCoach
SSCoach (19K reputation)SSCoach (19K reputation)SSCoach (19K reputation)SSCoach (19K reputation)SSCoach (19K reputation)SSCoach (19K reputation)SSCoach (19K reputation)SSCoach (19K reputation)

Group: General Forum Members
Points: 19033 Visits: 12426
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.


Hugo Kornelis, SQL Server MVP
Visit my SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
Andre Guerreiro
Andre Guerreiro
SSCrazy
SSCrazy (2.3K reputation)SSCrazy (2.3K reputation)SSCrazy (2.3K reputation)SSCrazy (2.3K reputation)SSCrazy (2.3K reputation)SSCrazy (2.3K reputation)SSCrazy (2.3K reputation)SSCrazy (2.3K reputation)

Group: General Forum Members
Points: 2301 Visits: 1515
I knew it had to do with the batch but I ended up choosing "0" as in "the whole batch will fail". Stupid me. :-D

Best regards,

Andre Guerreiro Neto

Database Analyst
http://www.softplan.com.br
MCITPx1/MCTSx2/MCSE/MCSA
wolfkillj
wolfkillj
SSCrazy
SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)SSCrazy (2.7K reputation)

Group: General Forum Members
Points: 2746 Visits: 2582
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
Blog: SQLSouth
Twitter: @SQLSouth
Raghavendra Mudugal
Raghavendra Mudugal
Hall of Fame
Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)

Group: General Forum Members
Points: 3386 Visits: 2958
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.
Tom Thomson
Tom Thomson
One Orange Chip
One Orange Chip (26K reputation)One Orange Chip (26K reputation)One Orange Chip (26K reputation)One Orange Chip (26K reputation)One Orange Chip (26K reputation)One Orange Chip (26K reputation)One Orange Chip (26K reputation)One Orange Chip (26K reputation)

Group: General Forum Members
Points: 26289 Visits: 12506
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

Raghavendra Mudugal
Raghavendra Mudugal
Hall of Fame
Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)Hall of Fame (3.4K reputation)

Group: General Forum Members
Points: 3386 Visits: 2958
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.
Rob Schripsema
Rob Schripsema
Hall of Fame
Hall of Fame (3.2K reputation)Hall of Fame (3.2K reputation)Hall of Fame (3.2K reputation)Hall of Fame (3.2K reputation)Hall of Fame (3.2K reputation)Hall of Fame (3.2K reputation)Hall of Fame (3.2K reputation)Hall of Fame (3.2K reputation)

Group: General Forum Members
Points: 3229 Visits: 11042
Great question!
Thanks!

Rob Schripsema
Propack, Inc.
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search