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

后端 未结 6 1610
借酒劲吻你
借酒劲吻你 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 18:23

    GO is like the end of a script.

    You could have multiple CREATE TABLE statements, separated by GO. It's a way of isolating one part of the script from another, but submitting it all in one block.


    BEGIN and END are just like { and } in C/++/#, Java, etc.

    They bound a logical block of code. I tend to use BEGIN and END at the start and end of a stored procedure, but it's not strictly necessary there. Where it IS necessary is for loops, and IF statements, etc, where you need more then one step...

    IF EXISTS (SELECT * FROM my_table WHERE id = @id)
    BEGIN
       INSERT INTO Log SELECT @id, 'deleted'
       DELETE my_table WHERE id = @id
    END
    

提交回复
热议问题