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

别等时光非礼了梦想. 提交于 2019-12-11 12:37:46

问题


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 **/


来源:https://stackoverflow.com/questions/37019512/why-shouldnt-transact-sql-statements-be-grouped-together-within-the-same-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!