CASE WHEN在SQL WHERE条件下非数值数据

时间:2012-05-01 23:27:34

标签: tsql conditional case-when

我有这个查询,但我需要第二个WHERE条件依赖于集合中的值:

SELECT TABLE1.*, TABLE2.*
FROM TABLE1, TABLE2
WHERE TABLE1.ID = TABLE2.ID
AND TABLE1.TIMESTAMP > DATEADD(D,-5,GETDATE())

所以我想要这样的东西不起作用(因为'>'):

SELECT TABLE1.*, TABLE2.*
FROM TABLE1, TABLE2
WHERE TABLE1.ID = TABLE2.ID
AND CASE WHEN TABLE1.TRIGGER = 'TRUE' THEN TABLE1.TIMESTAMP > DATEADD(D,-5,GETDATE()) END

我环顾四周,但我只能找到意图操纵数字信息的例子。有没有人有任何想法?

2 个答案:

答案 0 :(得分:2)

改变这个:

AND TABLE1.TIMESTAMP > DATEADD(D,-5,GETDATE())

致:

AND (TABLE1.TRIGGER <> 'TRUE' or (TABLE1.TRIGGER = 'TRUE' AND TABLE1.TIMESTAMP > DATEADD(D,-5,GETDATE()))

如果TABLE1.TRIGGER不等于TRUE,则此选项为“且为真”,如果TABLE1.TIMESTAMP > ...) em>等于TRUE

答案 1 :(得分:1)

CASE会产生一个值,因此您需要对其执行某些操作,例如将它与另一个值进行比较:

SELECT TABLE1.*, TABLE2.* 
  FROM TABLE1, TABLE2 
  WHERE TABLE1.ID = TABLE2.ID AND
    CASE
      WHEN TABLE1.TRIGGER = 'TRUE' THEN 1
      WHEN TABLE1.TIMESTAMP > DATEADD(D,-5,GETDATE()) THEN 1
      ELSE 0
      END = 1