I am trying to select data based on some parameters passed to my stored procedure. I have problems with the age, I am trying to do something like this:
If my stored procedure parameter @Age = 1 then I select age between 15 to 18, @Age = 2 then 19 – 25…, apparently this is incorrect, anyone can help. Thanks.:
SELECT
User
FROM
[Member] m
WHERE
((m.Gender = @Gender) or @Gender IS NULL)
and ((DATEDIFF(hour,m.DOB,GETDATE())/8766) Between
CASE
WHEN @Age = 1 THEN (SELECT DATEDIFF(hour, m.DOB, GETDATE())/8766 WHERE (SELECT DATEDIFF(hour, m.DOB, GETDATE())/8766) between 15 and 18)
WHEN @Age = 2 THEN (SELECT DATEDIFF(hour,m.DOB,GETDATE())/8766 WHERE (SELECT DATEDIFF(hour,m.DOB,GETDATE())/8766) between 19 and 25)
END)
I think this is what you are after (probably with some superfluous parenthesis):
If you’ve got a lot of clauses, it might be easier to read as (assuming a MemberID Primary Key)
Even better, you could add the ranges to a separate table called
AgeRangesYou could also make
DateDiff(hour, m.Dob, GetDate())/8766a computed column on your members table to simplify things (and make indexing possible if performance became an issue).