8

我怎么能在另一个 CTE 中调用 CTE?

WITH cte1
AS (
    SELECT City.*
    FROM City
    WHERE (City.CityName COLLATE SQL_Latin1_General_CP1_CI_AI) LIKE 'são paulo'
)
, cte2
AS (
    SELECT Imovel.Imovel_Id 
    FROM Imovel
    WHERE Imovel.Number = 311
    AND Imovel.ZIPCode = '30280490'
    AND Imovel.Complement = ''
    AND Imovel.Street = 'Do furquim'
        -- the line below has an error in cte.City_Id
    AND Imovel.City_Id = cte1.City_Id 
)
4

1 回答 1

18

您必须像普通表一样加入两者:

WITH cte1 
     AS (SELECT city.* 
         FROM   city 
         WHERE  ( city.cityname COLLATE sql_latin1_general_cp1_ci_ai ) LIKE 
                'são paulo'), 
     cte2 
     AS (SELECT imovel.imovel_id 
         FROM   imovel 
                INNER JOIN cte1 
                        ON imovel.city_id = cte1.city_id 
         WHERE  imovel.number = 311 
                AND imovel.zipcode = '30280490' 
                AND imovel.complement = '' 
                AND imovel.street = 'Do furquim') 
SELECT * FROM   cte2 

请注意,我已附加SELECT * FROM cte2,因为 CTE 不能“独立”。

于 2013-07-02T12:07:20.507 回答