1

I have the following query:

DECLARE @IsStocked bit
SELECT * FROM Products p WHERE p.LastSeen >  GETDATE() - 30 

This returns all Products that have been seen within the last 30 days.

My question is, I would like the p.LastSeen > GETDATE() - 30 clause to only apply when @IsStocked = true.

This is part of a larger query, and I'd like to achieve this without using IF/ELSE statements (i.e. if @IsStocked = false the p.LastSeen > GETDATE() - 30 section of the WHERE clause is ignored completely).

Thanks!

2
  • 1
    why don'y you want to use an IF/ELSE? The other alternative might lead to an incorrectly cached query plan.... Commented Sep 20, 2009 at 10:21
  • for simplicity really - there's around 10 variables in the sproc - all of which can be true/false or null - unless there is a way you can suggest that's not going to result in a IF/ELSE for each? thanks! Commented Sep 20, 2009 at 10:28

3 Answers 3

4
DECLARE @IsStocked bit

SELECT * FROM Products p
WHERE  @IsStocked = 0 OR (p.LastSeen > GETDATE() - 30);
Sign up to request clarification or add additional context in comments.

Comments

4
DECLARE @IsStocked bit;

SELECT * 
FROM Products p
WHERE (@IsStocked = 1 AND p.LastSeen > GETDATE() - 30) 
OR     @IsStocked = 0;

1 Comment

@Mitch: It's 6:30 AM and I can't get back to sleep. Gimme a break, man! ;-)
1

Here is my Query according to your question

DECLARE @IsStocked bit
Set @IsStocked=1
Select * from Product
Where LastSeen  = Case When (@IsStocked=1) THEN GETDATE() - 30 
                   Else LastSeen  END

hope that will help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.