When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

后端 未结 6 1599
借酒劲吻你
借酒劲吻你 2020-11-29 18:08

Can someone tell me when and where I need to use begin and end blocks in SQL Server?
Also, what exactly does the Go keyword do?

6条回答
  •  -上瘾入骨i
    2020-11-29 18:25

    GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".

    Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:

    CREATE DATABASE foo;
    USE foo;
    CREATE TABLE bar;
    

    because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:

    CREATE DATABASE foo;
    GO
    USE foo;
    CREATE TABLE bar;
    

提交回复
热议问题