SQL Server BEGIN/END vs BEGIN TRANS/COMMIT/ROLLBACK

前端 未结 5 946
自闭症患者
自闭症患者 2020-12-30 21:36

I have been trying to find info on the web about the differences between these statements, and it seems to me they are identical but I can\'t find confirmation of that or an

相关标签:
5条回答
  • 2020-12-30 22:08

    It should be mentioned, that there is a Begin; in PostgreSQL, that also initiates a transaction block, which at first confused me.

    http://www.postgresql.org/docs/9.0/static/sql-begin.html

    "BEGIN initiates a transaction block, that is, all statements after a BEGIN command will be executed in a single transaction until an explicit COMMIT or ROLLBACK is given. By default (without BEGIN), PostgreSQL executes transactions in "autocommit" mode, that is, each statement is executed in its own transaction and a commit is implicitly performed at the end of the statement (if execution was successful, otherwise a rollback is done)."

    0 讨论(0)
  • 2020-12-30 22:16

    The regular BEGIN and END are not used for transactions. Instead, they are just for indicating that some block of code is a single unit, much like braces {} in C#/C++/Java.

    If you have an IF statement or a WHILE loop that does 10 things, you need to enclose them in BEGIN/END so that SQL Server knows that that whole list of 10 statements should be executed as a part of that condition.

    0 讨论(0)
  • 2020-12-30 22:17

    These 2 statements are entirely different.

    BEGIN..END mark a block of code, eg in an if statement

    IF @something = 1
    BEGIN
      -- Do something when @something is equal to 1
    END
    

    BEGIN TRANS..COMMIT TRANS wrap the enclosing block in a transaction, and depending on server settings will rollback the transaction if an error occurs.

    0 讨论(0)
  • 2020-12-30 22:24

    I have not seen END TRANS :)

    i think we use END only for BEGIN keyword not for BEGIN trans we use commit or rollback for BEGIN trans

    0 讨论(0)
  • 2020-12-30 22:33

    BEGIN and END deal with code blocks. They are similar to the curly braces you see in many languages:

    if (somethingIsTrue)
    { // like BEGIN
        // do something here
    } // like END
    

    In SQL, this is:

    if somethingIsTrue
    BEGIN
        -- do something here
    END
    

    BEGIN TRAN, COMMIT, and ROLLBACK begin and end transactions. They do not specify a new block of code; they only mark the transaction boundaries.

    Note that you can write a BEGIN TRAN and COMMIT in separate blocks of code. For example, if you want code to be part of a transaction, but you don't want to start a new one if the code is already in a transaction, you can do something like this:

    declare @TranStarted bit = 0
    if @@trancount = 0
    begin
        set @TranStarted = 1
        begin tran
    end
    
    -- ... do work ...
    
    if @TranStarted = 1
    begin
        commit
        set @TranStarted = 0
    end
    
    0 讨论(0)
提交回复
热议问题