sql中GO语句可用可不用吗?什么时候有用?以及如何使用

来源:百度知道 编辑:UC知道 时间:2024/06/30 10:32:50
我是初学者,对SQL中的GO不是很清楚,大家帮忙解释一下,顺便举个例,谢谢

GO
向 SQL Server 实用工具发出一批 Transact-SQL 语句结束的信号。

例子1:
USE AdventureWorks;
GO
DECLARE @MyMsg VARCHAR(50)
SELECT @MyMsg = 'Hello, World.'
GO -- @MyMsg is not valid after this GO ends the batch.

-- Yields an error because @MyMsg not declared in this batch.
PRINT @MyMsg
GO

SELECT @@VERSION;
-- Yields an error: Must be EXEC sp_who if not first statement in
-- batch.
sp_who
GO

SQL Server 应用程序可以将多个 Transact-SQL 语句作为一个批发送到 SQL Server 的实例来执行。然后,该批中的语句被编译成一个执行计划。程序员在 SQL Server 实用工具中执行特殊语句,或生成 Transact-SQL 语句的脚本在 SQL Server 实用工具中运行时,使用 GO 作为批结束的信号。

例子2
USE AdventureWorks;
GO
DECLARE @NmbrContacts int
SELECT @NmbrContacts = COUNT(*)
FROM Person.Contact
PRINT 'The number of contacts as of ' +
CAST(GETDATE() AS char(20)) + ' is ' +
CAST(@NmbrContacts AS char (10))
GO