在检查web上的一些代码和SQL Server Management Studio生成的脚本时,我注意到一些语句以分号结束。
那么什么时候用呢?
在检查web上的一些代码和SQL Server Management Studio生成的脚本时,我注意到一些语句以分号结束。
那么什么时候用呢?
当前回答
分号似乎不应该与游标操作一起使用:OPEN, FETCH, CLOSE和DEALLOCATE。我在这上面浪费了几个小时。我仔细查看了BOL,并注意到[;]没有显示在这些游标语句的语法中!!
所以我有:
OPEN mycursor;
这给了我错误16916。
But:
OPEN mycursor
工作。
其他回答
分号似乎不应该与游标操作一起使用:OPEN, FETCH, CLOSE和DEALLOCATE。我在这上面浪费了几个小时。我仔细查看了BOL,并注意到[;]没有显示在这些游标语句的语法中!!
所以我有:
OPEN mycursor;
这给了我错误16916。
But:
OPEN mycursor
工作。
在SQL2008 BOL中,他们说在下一个版本中将需要分号。因此,要经常使用它。
参考:
Transact-SQL语法约定 SQL Server 2008 R2中已弃用的数据库引擎特性(“SQL Server未来版本不支持的特性”部分,“Transact-SQL”区域)
根据Transact-SQL语法约定(Transact-SQL) (MSDN)
Transact-SQL语句结束符。虽然在这个版本的SQL Server中,分号在大多数语句中都不是必需的,但在未来的版本中,分号将是必需的。
(另见@gerryLowry的评论)
你必须使用它。
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
分号在复合SELECT语句中并不总是有效。
比较一个普通复合SELECT语句的两个不同版本。
的代码
DECLARE @Test varchar(35);
SELECT @Test=
(SELECT
(SELECT
(SELECT 'Semicolons do not always work fine.';);););
SELECT @Test Test;
返回
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ';'.
然而,代码
DECLARE @Test varchar(35)
SELECT @Test=
(SELECT
(SELECT
(SELECT 'Semicolons do not always work fine.')))
SELECT @Test Test
返回
Test
-----------------------------------
Semicolons do not always work fine.
(1 row(s) affected)