SQL Server: Do I need to use GO statements between

2020-02-27 06:11发布

问题:

I have seen people use GO statement between batches of SQL code, but AFAICS it is not mandatory (SQL Server 2008). What are the benefits using GO statements between batches/sets of SQL statements?

回答1:

They're not strictly required - they're just instructions for the SQL Server Management Studio to execute the statements up to this point now and then keep on going. GO is not a T-SQL keyword or anything - it's just an instruction that works in SSMS.

Sometimes, you need a GO - e.g. if you add a column to a table, and then want to select it again, you need to have a GO between the adding of the column, and the query of it.

E.g. if you try to execute this, you'll get errors from SSMS:

ALTER TABLE (sometable) ADD DateTimeStamp DATETIME

SELECT ID, DateTimeStamp FROM (sometable) WHERE ID > 5

Results in:

Msg 207, Level 16, State 1, Line 9 Invalid column name 'datetimestamp'.

The point is: SSMS is trying to verify the whole statement at once, but on the SELECT statement, it will complain about the missing DateTimeStamp column.

ALTER TABLE (sometable) ADD DateTimeStamp DATETIME
GO       

SELECT ID, DateTimeStamp FROM (sometable) WHERE ID > 5

If you put a GO between the two statements, it'll work, because SSMS won't parse and verify the whole statement ahead of time - it will do the first part, and then only parse the second (after the GO).

But other than situations like this one, GO is hardly ever required.



回答2:

It's only mandatory in SQL tools to tell SSMS where the batch start and end is. It's also required for some statements such as CREATE TRIGGER which must the first in the batch

For example, in a c# to SQL Server call it has no meaning