SQL Server:批处理语句(即使用“GO")有什么用? [英] SQL Server: What are batching statements (i.e. using "GO") good for?

查看:17
本文介绍了SQL Server:批处理语句(即使用“GO")有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 SQL Server GO 被认为是批处理分隔符.

I know that in SQL Server GO is considered a batch separator.

我的问题是:拥有批处理分隔符有什么意义?它能给您带来什么好处?为什么要使用它?

My question is: What is the point of having a batch separator? What benefit does it give you and why would you want to use it?

示例:我经常看到它在 SQL 代码中使用如下,但我不明白为什么它会被视为最佳实践.据我所知,如果没有所有 GO 语句,代码会是一样的:

Example: I've often seen it used in SQL code as follows and I can't see why it would be considered a best practice. As far as I can tell the code would the same without all the GO statements:

USE AdventureWorks2012;
GO
BEGIN TRANSACTION;
GO
IF @@TRANCOUNT = 0
BEGIN
    SELECT FirstName, MiddleName 
    FROM Person.Person WHERE LastName = 'Adams';
    ROLLBACK TRANSACTION;
    PRINT N'Rolling back the transaction two times would cause an error.';
END;
ROLLBACK TRANSACTION;
PRINT N'Rolled back the transaction.';
GO

(来源:technet 文档):

推荐答案

在示例中,它没有任何用处.

In the example there it is of no use whatsoever.

然而,批处理中必须只有很多语句.

Lots of statements must be the only ones in the batch however.

CREATE PROCEDURE.

通常在进行架构更改(例如,向现有表中添加新列)之后,使用新架构的语句必须在不同的批处理中单独编译.

Also often after making schema changes (e.g. adding a new column to an existing table) statements using the new schema must be compiled separately in a different batch.

通常,提交由 GO 分隔的单独批次的替代方法是使用 EXEC

Generally an alternative to submitting separate batches separated by GO is to execute the SQL in a child batch using EXEC

这篇关于SQL Server:批处理语句(即使用“GO")有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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