Can we use 'GO' multiple times in SQL Transaction?

前端 未结 3 2331
旧时难觅i
旧时难觅i 2021-02-18 21:15

Can We use GO statement mutiple times in a SQL Transaction. I am having a long T-SQL script and I want to run it in a SQL Transaction. If

3条回答
  •  后悔当初
    2021-02-18 21:28

    Note that GO is not a SQL keyword. It is a client-side batch separator used by SQL Server Management Studio and other client tools.

    GO has no effect on transaction scope. BEGIN TRAN will start a transaction on the current connection. COMMIT and ROLLBACK will end the transaction. You can execute as many statements as you want in-between. GO will execute the statements separately.

    As specified by MSDN:

    A TRY…CATCH construct cannot span multiple batches.

    So BEGIN TRY, END TRY, BEGIN CATCH, and END CATCH cannot be separated into separate batches by a GO separator. They must appear in the same query.

    If you do try to include a batch separator in a TRY/CATCH statement like the invalid SQL below:

    begin try
        go
    end try
    begin catch
        go
    end catch
    

    This will execute 3 different queries that return syntax errors:

    1) begin try

    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near 'begin'.
    

    2) end try begin catch

    Msg 102, Level 15, State 1, Line 3
    Incorrect syntax near 'try'.
    

    3) end catch

    Msg 102, Level 15, State 1, Line 6
    Incorrect syntax near 'catch'.
    

提交回复
热议问题