Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase «««1234»»

Triggers 1 Expand / Collapse
Author
Message
Posted Friday, April 19, 2013 7:29 AM
UDP Broadcaster

UDP BroadcasterUDP BroadcasterUDP BroadcasterUDP BroadcasterUDP BroadcasterUDP BroadcasterUDP BroadcasterUDP Broadcaster

Group: General Forum Members
Last Login: Tuesday, September 2, 2014 11:51 AM
Points: 1,477, Visits: 254
Good question!
Thanks,
Lon
Post #1444387
Posted Friday, April 19, 2013 7:59 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Monday, November 10, 2014 6:19 AM
Points: 262, Visits: 919
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)
Post #1444418
Posted Friday, April 19, 2013 8:01 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Monday, September 15, 2014 11:49 AM
Points: 1,848, Visits: 587
Thanks for the excellent question Hugo..
learnt something new..
Post #1444420
Posted Friday, April 19, 2013 8:16 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: 2 days ago @ 5:21 AM
Points: 6,098, Visits: 8,367
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
Post #1444434
Posted Friday, April 19, 2013 8:33 AM


SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: Monday, November 10, 2014 3:37 AM
Points: 904, Visits: 1,491
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
Post #1444452
Posted Friday, April 19, 2013 8:35 AM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Tuesday, October 28, 2014 12:50 PM
Points: 1,061, Visits: 2,580
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
Post #1444455
Posted Friday, April 19, 2013 10:06 AM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Yesterday @ 9:55 AM
Points: 1,038, Visits: 2,342
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.
Post #1444501
Posted Friday, April 19, 2013 10:54 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Yesterday @ 9:35 AM
Points: 7,874, Visits: 9,613
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
Post #1444519
Posted Friday, April 19, 2013 11:28 AM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Yesterday @ 9:55 AM
Points: 1,038, Visits: 2,342
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.
Post #1444545
Posted Friday, April 19, 2013 3:08 PM


SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Tuesday, November 18, 2014 12:51 PM
Points: 2,010, Visits: 10,969
Great question!
Thanks!



Rob Schripsema
Accelitec, Inc
Post #1444620
« Prev Topic | Next Topic »

Add to briefcase «««1234»»

Permissions Expand / Collapse