• Krishna1 (4/22/2014)


    I need the insert of table a and c to be successful even though insert to be fails.

    code sample

    drop table a

    go

    create table a

    (a1 integer identity, a2 integer)

    go

    drop table b

    go

    create table b

    (b1 integer identity, b2 integer)

    go

    drop table c

    go

    create table c

    (c1 integer identity, c2 integer)

    go

    CREATE TRIGGER [TRaInsert]

    ON [a]

    FOR INSERT

    AS

    BEGIN TRY

    begin transaction c

    begin try

    begin transaction b

    insert into b (b2) values(1)

    select 1/0 -- error created

    commit transaction b

    end try

    begin catch

    print 'catch of transaction b'

    rollback transaction b

    end catch

    insert into c (c2) values(1)

    commit transaction c

    end try

    begin catch

    select ERROR_MESSAGE()

    end catch

    go

    You can't do this like this at all. There is no such thing as nested transactions, they are a complete farce. An insert statement is inside of an implicit transaction. As soon as you issue a rollback anywhere it will rollback the outer most transaction and reset @@trancount to 0. When you start a nested transaction all that actually happens is @@trancount is increased by 1.

    You could probably wrap each of your inserts inside of a try catch but no transactions. I realize your example was simplified for posting but why do you have to do so much work inside of a trigger? Also, you need to be sure that your real trigger logic is set based so it can handle multiple row inserts. Keep in mind that triggers can cause lots of performance issues in sql server if they are not setup correctly.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/