Why shouldn't Transact-SQL statements be group

2019-07-22 07:27发布

问题:

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?

回答1:

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.



回答2:

BEGIN..END is not a visual option in order to be able to collapse a region, you're actually telling the server that these bunch of lines are together. Using it as a #region like is just a Workaround.

This is because Whatever is between the BEGIN and END Will be executed as a Batch, and all the rules of a batch will apply to it.

Think of what will happen when an error occurs in one of the statements, do you want the other statements to continue ?

Check More here : Batches



回答3:

You can use comments to distinguish different batches like the below.

BEGIN /** Region1 Starts**/
....
....
....
END /** Region1 ends**/

BEGIN /** Region2 Starts **/
....
....
....
END /** Region2 Ends **/