在WHERE CLAUSE中的情况?

时间:2012-11-19 13:00:16

标签: sql sql-server

我有一个有趣的问题。我将编写一个标量值函数。其中一个参数不在表列中。我必须在where子句中使用此参数(@ImpUrgPri)。对于该参数,将存在表中存在列的条件。你能帮帮我吗?

DECLARE @ImpUrgPri NVARCHAR(3)
SET @ImpUrgPri = 'URG'
DECLARE @Enum INT
SET @Enum = 0

select COUNT(*) 
from zODYA_vwCallReq_AllData 
where ActiveFlag = 1
AND 
(CASE WHEN (@ImpUrgPri = 'PRI') THEN Priority_Enum == @Enum
        WHEN (@ImpUrgPri = 'URG') THEN Urgency_Enum == @Enum 
        WHEN (@ImpUrgPri = 'IMP') THEN Impact_Enum == @Enum END)

group by 
(CASE WHEN (@ImpUrgPri = 'PRI') THEN Priority_Enum 
        WHEN (@ImpUrgPri = 'URG') THEN Urgency_Enum 
        WHEN (@ImpUrgPri = 'IMP') THEN Impact_Enum END)

3 个答案:

答案 0 :(得分:1)

您的选择可以是:

select COUNT(*) 
from zODYA_vwCallReq_AllData 
where ActiveFlag = 1
AND @Enum =  (CASE WHEN (@ImpUrgPri = 'PRI') THEN Priority_Enum
             WHEN (@ImpUrgPri = 'URG') THEN Urgency_Enum
             WHEN (@ImpUrgPri = 'IMP') THEN Impact_Enum END)

group by 
(CASE WHEN (@ImpUrgPri = 'PRI') THEN Priority_Enum 
        WHEN (@ImpUrgPri = 'URG') THEN Urgency_Enum 
        WHEN (@ImpUrgPri = 'IMP') THEN Impact_Enum END)

答案 1 :(得分:0)

我认为最好使用IF并且有三个不同的SELECT s,每个“当”的情况下都有一个。

您还可以动态创建SQL(在存储过程内),这会使存储过程稍微缩短。只有这里的三个选项,我会坚持使用3个SELECT。

答案 2 :(得分:0)

DECLARE @ImpUrgPri NVARCHAR(3)
SET @ImpUrgPri = 'URG'
DECLARE @Enum INT
SET @Enum = 0

select COUNT(*) 
from zODYA_vwCallReq_AllData 
where ActiveFlag = 1
AND 
(CASE @ImpUrgPri
    WHEN 'PRI' THEN Priority_Enum
    WHEN 'URG' THEN Urgency_Enum
    WHEN 'IMP' THEN Impact_Enum
END) = @Enum
group by 
(CASE @ImpUrgPri
    WHEN 'PRI' THEN Priority_Enum
    WHEN 'URG' THEN Urgency_Enum
    WHEN 'IMP' THEN Impact_Enum
END)