Question

I have this query but I need the second WHERE condition to be dependent on a value in the set:

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

So I was going for something like this which doesn't work (because of the '>'):

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

I've looked around but I was only able to find examples where the intention was to manipulate numerical info. Does anyone have any ideas?

Was it helpful?

Solution

Change this:

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

To:

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

This will either be "and true" if TABLE1.TRIGGER is not equal to TRUE, or it will perform your extra conditional check (TABLE1.TIMESTAMP > ...) if it is equal to TRUE.

OTHER TIPS

CASE results in a value, so you need to do something with it, e.g. compare it to another value:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top