CTE在CASE EXIST中返回错误的值

时间:2013-07-01 19:04:50

标签: sql sql-server tsql

如果某个城市中存在特定邻居,我想要恢复一个布尔值

城市

City_Id | State_Id | CityName
1         6          São Paulo
2         22         São Paulo
3         26         São Paulo

邻居

Neighbor_Id | City_Id | NeighborName

查询

WITH cte
AS (
    SELECT City.*
    FROM City
    WHERE (City.CityName COLLATE SQL_Latin1_General_CP1_CI_AI) LIKE 'são paulo'
)
SELECT cte.*
    ,CASE 
    WHEN EXISTS (
            SELECT Neighbor.City_Id 
            FROM Neighbor
            INNER JOIN cte ON Neighbor.City_Id = cte.city_id
            WHERE (Neighbor.NeighborName COLLATE SQL_Latin1_General_CP1_CI_AI) LIKE 'ademar'
        )
        THEN 1
        ELSE 0
    END AS F
FROM cte

结果

City_Id | State_Id | CityName   | f
1         6          São Paulo    1
2         22         São Paulo    1
3         26         São Paulo    1

错误

我知道在City_Id 2中我的表中没有任何邻居有这个城市ID,所以当城市ID = 2时,为什么在CASE EXISTS中返回1?

2 个答案:

答案 0 :(得分:2)

您的问题正在发生,因为您要在子查询中单独链接到cte - 它不会针对主查询中特定行的cte检查邻居的值,但是而是反对整个 cte。相反,请尝试将F的表达式更改为:

CASE 
WHEN EXISTS (
        SELECT Neighbor.City_Id 
        FROM Neighbor
        WHERE Neighbor.City_Id = cte.city_id and
              (Neighbor.NeighborName COLLATE SQL_Latin1_General_CP1_CI_AI) LIKE 'ademar'
    )
    THEN 1
    ELSE 0
END AS F

答案 1 :(得分:1)

为什么不进行实际测试

WITH cte
AS (
    SELECT City.*
    FROM City
    WHERE (City.CityName COLLATE SQL_Latin1_General_CP1_CI_AI) LIKE 'são paulo'
)
            SELECT Neighbor.City_Id 
            FROM Neighbor
            INNER JOIN cte ON Neighbor.City_Id = cte.city_id
            WHERE (Neighbor.NeighborName COLLATE SQL_Latin1_General_CP1_CI_AI) LIKE 'ademar'