简体   繁体   中英

Transaction in Stored procedure

Please can someone help.

I have several stored procedures in a job, and In one of them I Begin a transaction to delete some rows and if rows are greater than 10 then I Roll back. however if there are not I don't want to commit straight away, because 2 stored procedure later I do something similar. however if count is greater than 10 in this instance I want it rolled back all the way to when I stared the transaction (two stored procedures ago)

Is it possible to start a transaction in a store procedure and have multiple roll backs and Commit right at the end somewhere or do I have to put all the code into 1 store procedure to do that?

You can use @@TRANCOUNT to determine whether or not you have any outstanding uncommitted transactions and then use that to dictate the logic of your stored procedures.

CREATE PROCEDURE Proc1
AS
BEGIN
    BEGIN TRANSACTION
    // DO STUFF
    IF (@@ROWCOUNT > 10)
        ROLLBACK TRANSACTION
END

CREATE PROCEDURE Proc2
AS
BEGIN
    IF (@@TRANCOUNT > 0)
    BEGIN
        // DO STUFF
        IF (@@ROWCOUNT > 10)
            ROLLBACK TRANSACTION
    END
END

CREATE PROCEDURE Proc3
AS
BEGIN
    IF (@@TRANCOUNT > 0)
    BEGIN
        // DO STUFF
        IF (@@ROWCOUNT > 10)
            ROLLBACK TRANSACTION
        ELSE
            COMMIT TRANSACTION
    END
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM