且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server:我需要在批次之间使用 GO 语句吗?

更新时间:2023-02-07 09:36:16

它们不是严格要求的 - 它们只是 SQL Server Management Studio 执行语句到现在为止然后继续执行的指令.GO 不是一个 T-SQL 关键字或任何东西 - 它只是一个在 SSMS 中工作的指令.

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.

有时,您需要 GO - 例如如果你在表中添加一列,然后想再次选择它,你需要在添加列和查询它之间有一个 GO.

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.

例如如果您尝试执行此操作,则会收到来自 SSMS 的错误:

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

结果:

消息 207,级别 16,状态 1,第 9 行列名日期时间戳"无效.

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

重点是:SSMS 试图一次验证整个语句,但是在 SELECT 语句上,它会抱怨缺少 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

如果你在两个语句之间放一个 GO,它会起作用,因为 SSMS 不会提前解析和验证整个语句 - 它会做第一部分,然后只做解析第二个(在 GO 之后).

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).

但除了这种情况,几乎不需要 GO.

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