sql-servert-sqltechnet

Why shouldn't Transact-SQL statements be grouped together within the same batch?


The BEGIN...END description of TechNet make me confused with following remark:

Although all Transact-SQL statements are valid within a BEGIN...END block, certain Transact-SQL statements should not be grouped together within the same batch (statement block).

https://technet.microsoft.com/en-us/library/aa225998(v=sql.80).aspx

Could anybody tell me why they shouldn't be grouped within a BEGIN ... END block? Is there any problem when I use BEGIN...END to create region as this suggestion: sql server #region?


Solution

  • If you need to create multiple batches in T-SQL script, you need to separate the group of commands explicitly with the GO statement. So BEGIN...END block (batch) is created implicitly even if you do not add it explicitly to your code. So adding it explicitly shoud not create any additional troubles for you.

    Certain commands cannot be grouped together in one batch, as specified in the linked MSDN article:

    CREATE DEFAULT, CREATE FUNCTION, CREATE PROCEDURE, CREATE RULE, CREATE TRIGGER, and CREATE VIEW statements cannot be combined with other statements in a batch. The CREATE statement must begin the batch. All other statements that follow in that batch will be interpreted as part of the definition of the first CREATE statement.

    A table cannot be altered and then the new columns referenced in the same batch.

    If an EXECUTE statement is the first statement in a batch, the EXECUTE keyword is not required. The EXECUTE keyword is required if the EXECUTE statement is not the first statement in the batch.