【问题标题】:Common Table Expression, why semicolon?公用表表达式,为什么要分号?
【发布时间】:2011-10-19 18:21:54
【问题描述】:

通常在SQL ServerCommon Table Expression 子句的语句前面有分号,像这样:

;WITH OrderedOrders AS --semicolon here
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
    FROM Sales.SalesOrderHeader 
) 
SELECT * 
FROM OrderedOrders 
WHERE RowNumber BETWEEN 50 AND 60

为什么?

【问题讨论】:

    标签: sql sql-server tsql sql-server-2008 common-table-expression


    【解决方案1】:
    • 为了避免歧义,因为 WITH 可以在其他地方使用
      ..FROM..WITH (NOLOCK)..
      RESTORE..WITH MOVE..
    • 在 SQL Server 中使用; 终止语句是可选的

    综上所述,前面的语句必须在 WITH/CTE 之前终止。为了避免错误,大多数人使用;WITH,因为我们不知道 CTE 之前是什么

    所以

    DECLARE @foo int;
    
    WITH OrderedOrders AS
    (
        SELECT SalesOrderID, OrderDate,
    ...;
    

    和

    一样
    DECLARE @foo int
    
    ;WITH OrderedOrders AS
    (
        SELECT SalesOrderID, OrderDate,
    ...;
    

    MERGE 命令也有类似的要求。

    【讨论】:

    • 一个快速简洁的答案,非常好。我会花半天时间或半英里页面(有点夸张,但不过分)。说英语作为第二语言的“好处”...
    • 对于较新的版本 - The SQL Server documentation indicates that not terminating T-SQL statements with a semicolon is a deprecated feature. This means that the long-term goal is to enforce use of the semicolon in a future version of the product. - Miscrosoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan.
    • Microsoft 已弃用缺少的分号十多年,并承诺在“未来版本”中需要它。良好的做法是始终使用终止分号,就像所有其他数据库一样。除此之外,在这种情况下,这将消除对古怪的前导分号的需要。
    • @Manngo 同意,但有时它只是防御性编程,尤其是在共享开发环境中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多