在检查web上的一些代码和SQL Server Management Studio生成的脚本时,我注意到一些语句以分号结束。

那么什么时候用呢?


当前回答

你必须使用它。

The practice of using a semicolon to terminate statements is standard and in fact is a requirement in several other database platforms. SQL Server requires the semicolon only in particular cases—but in cases where a semicolon is not required, using one doesn’t cause problems. I strongly recommend that you adopt the practice of terminating all statements with a semicolon. Not only will doing this improve the readability of your code, but in some cases it can save you some grief. (When a semicolon is required and is not specified, the error message SQL Server produces is not always very clear.)

最重要的是:

SQL Server文档指出,不能用 分号是不赞成使用的特性。这意味着长期目标是强制使用 该产品的未来版本中的分号。这又多了一个进入 终止所有语句的习惯,即使目前不需要。

来源:Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan


举例说明为什么你总是必须使用;下面是两个查询(复制自这篇文章):

BEGIN TRY
    BEGIN TRAN
    SELECT 1/0 AS CauseAnException
    COMMIT
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE()
    THROW
END CATCH

BEGIN TRY
    BEGIN TRAN
    SELECT 1/0 AS CauseAnException;
    COMMIT
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE();
    THROW
END CATCH

其他回答

摘自Ken Powers在SQLServerCentral.Com上的文章:

分号

分号字符是语句结束符。它是ANSI SQL-92标准的一部分,但从未在Transact-SQL中使用过。事实上,编写T-SQL代码好几年都不会遇到分号。

使用

有两种情况必须使用分号。第一种情况是使用公共表表达式(CTE),而CTE不是批处理中的第一个语句。第二种情况是您发出一个servicebroker语句,而servicebroker语句不是批处理中的第一个语句。

分号似乎不应该与游标操作一起使用:OPEN, FETCH, CLOSE和DEALLOCATE。我在这上面浪费了几个小时。我仔细查看了BOL,并注意到[;]没有显示在这些游标语句的语法中!!

所以我有:

OPEN mycursor;

这给了我错误16916。

But:

OPEN mycursor

工作。

你必须使用它。

The practice of using a semicolon to terminate statements is standard and in fact is a requirement in several other database platforms. SQL Server requires the semicolon only in particular cases—but in cases where a semicolon is not required, using one doesn’t cause problems. I strongly recommend that you adopt the practice of terminating all statements with a semicolon. Not only will doing this improve the readability of your code, but in some cases it can save you some grief. (When a semicolon is required and is not specified, the error message SQL Server produces is not always very clear.)

最重要的是:

SQL Server文档指出,不能用 分号是不赞成使用的特性。这意味着长期目标是强制使用 该产品的未来版本中的分号。这又多了一个进入 终止所有语句的习惯,即使目前不需要。

来源:Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan


举例说明为什么你总是必须使用;下面是两个查询(复制自这篇文章):

BEGIN TRY
    BEGIN TRAN
    SELECT 1/0 AS CauseAnException
    COMMIT
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE()
    THROW
END CATCH

BEGIN TRY
    BEGIN TRAN
    SELECT 1/0 AS CauseAnException;
    COMMIT
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE();
    THROW
END CATCH

当在包含其他语句的批处理中使用DISABLE或ENABLE TRIGGER语句时,它前面的语句必须以分号结束。否则,您将得到一个语法错误。我用这个把头发都扯掉了……后来,我偶然发现了这个MS Connect项目。它关闭了,无法修复。

在这里看到的

如果你想在SQLServer中得到随机的命令超时错误,那么在CommandText字符串的末尾去掉分号。

我不知道这是否在任何地方都有记录,或者这是否是一个错误,但它确实发生了,我从痛苦的经验中学到了这一点。

我有可验证的和可重复的例子使用SQLServer 2008。

在实践中,即使你只是向数据库发送一条语句,也要包含结束符。