我可以使用多个“ with”吗?


198

例如:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

With lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

...不起作用。“错误附近”。

另外,我想先用在里面,再用在里面。是真实的还是我需要使用临时表?


1
BOL也具有确切的语法。msdn.microsoft.com/zh-cn/library/ms175972%28v=SQL.100%29.aspx注意[ ,...n ]
CVn

Answers:


342

尝试:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

是的,您可以在通用表表达式定义内引用通用表表达式。甚至递归地。这导致一些非常巧妙的技巧


30
对于那些没有像我这样立即注意到的人,这里的问题是在原始with语句之后添加一个逗号
。.lol

11
而不是写的字with
user230910

嗨,这等效于两个表之间的交叉联接。还是这样做创建两个单独的表。我不想交叉连接两个非常大的表,有没有一种方法可以有效地创建两个单独的“ with”表
Long Le

1
@LongLe不,它们不等同于联接,也不是表。这些是CTE-公用表表达式。它们更像是……可以像表一样使用的命名查询……或更像是视图。请谷歌他们。他们很整洁。它是最好的标准SQL功能之一,可以极大地帮助使复杂的查询易于理解并受到控制。
Tomek Szpakowicz

对于那些不知道什么是“公用表表达式”的人,在给定的示例中,它们是“ DependencedIncidents”和“ lalala”。有关详细信息,请参阅docs.microsoft.com/zh-cn/sql/t-sql/queries/…
亨利·杨

110

是的-只需这样:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

您不需要重复WITH关键字


13
lalala可以使用DependencydIncidents吗?
布伦

依赖事件可以使用拉拉吗?
亨利·杨

3
@HenryYang:否-更高版本的CTE(lalala)可以使用之前定义的任何CTE- 但更早版本的CTE()不能使用仅稍后定义的CTE ...
marc_s
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.