即使未满足WHERE子句,也会从查询返回结果

时间:2014-08-27 14:55:44

标签: sql sql-server ibatis.net

我正在创建一个确保满足某些约束的查询。这是现在的半工作版本:

SELECT CASE
            WHEN TaskId IS NULL THEN 0
            ELSE 1  
        END AS TaskExists, 
        CASE
            WHEN IsDownTask = 0 AND TaskStatus = 63 THEN 1
            WHEN IsDownTask = 1 THEN 1
            ELSE 0
        END AS PressReady,
        CASE 
            WHEN IsDownTask = 1 AND MachineId <> 2710 THEN 1
            ELSE 0
        END AS DownTaskAssignedToDifferentMachine   
FROM Task T
WHERE TaskId = 555555

TaskId表中存在Task时,此方法正常,但如果该任务不存在(因此TaskExists字段),我还需要返回值。

对于不存在的任务的查询,我希望返回

  • TaskExists 0
  • PressReady 0
  • DownTaskAssignedToDisfferentMachine 0

即使没有TaskId存在,如何修改我的查询以返回此信息?

4 个答案:

答案 0 :(得分:15)

如果您想要返回这些值,只需使用SUMISNULL包裹每一列:

SELECT ISNULL(SUM(CASE
        WHEN TaskId IS NULL THEN 0
        ELSE 1  
    END), 0) AS TaskExists, 
    ISNULL(SUM(CASE
        WHEN IsDownTask = 0 AND TaskStatus = 63 THEN 1
        WHEN IsDownTask = 1 THEN 1
        ELSE 0
    END), 0) AS PressReady,
    ISNULL(SUM(CASE 
        WHEN IsDownTask = 1 AND MachineId <> 2710 THEN 1
        ELSE 0
    END), 0) AS DownTaskAssignedToDifferentMachine    

答案 1 :(得分:1)

您可以尝试这样的事情:

DECLARE @task INT
SET @task = 555555

SELECT CASE
            WHEN TaskId IS NULL THEN 0
            ELSE 1  
        END AS TaskExists, 
        CASE
            WHEN IsDownTask = 0 AND TaskStatus = 63 THEN 1
            WHEN IsDownTask = 1 THEN 1
            ELSE 0
        END AS PressReady,
        CASE 
            WHEN IsDownTask = 1 AND MachineId <> 2710 THEN 1
            ELSE 0
        END AS DownTaskAssignedToDifferentMachine   
FROM Task T
WHERE TaskId = @task
UNION ALL 
SELECT 0 TaskExists, 0 PressReady, 0 DownTaskAssignedToDifferentMachine   
WHERE NOT EXISTS (SELECT * FROM  Task WHERE TaskId = @task)

答案 2 :(得分:1)

如果它必须在查询中,而不是在代码中,那么只需在查询结尾处欺骗并固定默认行。保证默认值在任何可能的真实结果之后排序,并限制在第一行:

SELECT TOP 1 * FROM (
  SELECT 1 AS TaskExists, CASE ... END AS PressReady, CASE ... AS WowYouHaveALongFieldNameHere
    FROM Task
   WHERE TaskID = 55555

  UNION

  -- default if no matching row
  SELECT 0,               0,                          0
) ORDER BY TaskExists DESC;

您可能会发现这比涉及聚合函数或强制连接和COALESCE / ISNULLING等的替代方案更具可读性。

答案 3 :(得分:-1)

请尝试以下代码。我没有经过测试。

SELECT CASE
                WHEN TaskId IS NULL THEN 0
                ELSE 1  
            END AS TaskExists, 
            CASE
                WHEN IsDownTask = 0 AND TaskStatus = 63 THEN 1
                WHEN IsDownTask = 1 THEN 1
                ELSE 0
            END AS PressReady,
            CASE 
                WHEN IsDownTask = 1 AND MachineId <> 2710 THEN 1
                ELSE 0
            END AS DownTaskAssignedToDifferentMachine   
    FROM Task T
    WHERE  1= case when TaskId = 555555 then 1 
    else 0 end