Can you create nested WITH clauses for Common Table Expressions?

后端 未结 7 1171
花落未央
花落未央 2020-12-12 10:42
WITH y AS (
    WITH x AS (
        SELECT * FROM MyTable
    )
    SELECT * FROM x
)
SELECT * FROM y

Does something like this work? I tried it ear

相关标签:
7条回答
  • 2020-12-12 11:34

    You can do the following, which is referred to as a recursive query:

    WITH y
    AS
    (
      SELECT x, y, z
      FROM MyTable
      WHERE [base_condition]
    
      UNION ALL
    
      SELECT x, y, z
      FROM MyTable M
      INNER JOIN y ON M.[some_other_condition] = y.[some_other_condition]
    )
    SELECT *
    FROM y
    

    You may not need this functionality. I've done the following just to organize my queries better:

    WITH y 
    AS
    (
      SELECT * 
      FROM MyTable
      WHERE [base_condition]
    ),
    x
    AS
    (
      SELECT * 
      FROM y
      WHERE [something_else]
    )
    SELECT * 
    FROM x
    
    0 讨论(0)
提交回复
热议问题