公共表表达式,为什么要用分号?

发布于 2024-11-27 18:02:22 字数 331 浏览 0 评论 0原文

通常在SQL Server公共表表达式子句中,语句前面有分号,如下所示:

;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

为什么?

Usually in SQL Server Common Table Expression clause there is semicolon in front of the statement, like this:

;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

Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光暖心i 2024-12-04 18:02:22
  • 避免歧义,因为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 命令具有类似的要求

  • To avoid ambiguity because WITH can be used elsewhere
    ..FROM..WITH (NOLOCK)..
    RESTORE..WITH MOVE..
  • It's optional to terminate statements with ; in SQL Server

Put together, the previous statement must be terminated before a WITH/CTE. To avoid errors, most folk use ;WITH because we don't know what is before the CTE

So

DECLARE @foo int;

WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
...;

is the same as

DECLARE @foo int

;WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
...;

The MERGE command has a similar requirement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文