SQL Server:我需要在批次之间使用 GO 语句吗? [英] SQL Server: Do I need to use GO statements between batches?

查看:26
本文介绍了SQL Server:我需要在批次之间使用 GO 语句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过人们在批量 SQL 代码之间使用 GO 语句,但 AFAICS 不是强制性的(SQL Server 2008).在批处理/组 SQL 语句之间使用 GO 语句有什么好处?

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?

推荐答案

它们不是严格要求的 - 它们只是 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.

这篇关于SQL Server:我需要在批次之间使用 GO 语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆