I have a Scenario in my SQL query is that I have to find out babies records with given dates but from multiple years Suppose My Selection Date is = 01/Jan/2014 to 31/Jan/2014
I have another parameter that is year, that it asks me randomly to select data of babies born of previous (1~3 Years) Suppose If my current Selected dates are of Years 2014 and my year variable has value 2 then
I must bring data of babies respectively to the current year and also a year less then of current date and so on Below is my Given Scenario
--------------------------------------------
-- BABIES_TABLE
ID | Name | Age | DOB |
--------------------------------------------
1 JKL 3 21/Jan/2012
2 DEF 2 09/Jan/2013
3 ABC 1 04/Jan/2014
4 XYZ 1 02/Feb/2014
-- Date Range [01/Jan/2014 - 31/Jan/2014]
-- Year = 2
---------------------------------------------
ID | Name | Age | DOB |
---------------------------------------------
3 ABC 1 04/Jan/2014
2 DEF 2 09/Jan/2013
-- Date Range [01/Jan/2014 - 31/Jan/2014]
-- Year = 3
---------------------------------------------
ID | Name | Age | DOB |
---------------------------------------------
3 ABC 1 04/Jan/2014
2 DEF 2 09/Jan/2013
1 JKL 3 21/Jan/2012
below is my SQl Query which is ambiguous and having error.I have try with single date comparison , Its fine But when i add OR condition, it gives me error
--MY SQL Query is Below
DECLARE @startDate AS DATETIME
DECLARE @enddate AS DATETIME
DECLARE @y AS INT
SET @startDate='2012-10-12'
SET @enddate='2012-10-20'
SET @y=2
SELECT * FROM BABIES_TABLE
WHERE
CAST(CONVERT(VARCHAR, BABIES_TABLE.DOB, 111) AS DATETIME) >= CASE
--If entered Year = 1
WHEN @y = 1 THEN
(@startDate)
--If entered Year = 2
WHEN @y = 2 THEN
CASE
(@startDate)
END
OR
CASE
YEAR(@startDate-1)
END
WHEN @y = 3 THEN
CASE
(@startDate)
END
OR
CASE
YEAR(@startDate-1)
END
OR
CASE
YEAR(@startDate-2)
END
END
END
AND
CAST(CONVERT(VARCHAR, BABIES_TABLE.DOB, 111) AS DATETIME) <= CASE
WHEN @y = 1 THEN
(@enddate)
WHEN @y = 2 THEN
CASE
(@enddate)
END
OR
CASE
YEAR(@enddate-1)
END
WHEN @y = 3 THEN
CASE
(@enddate)
END
OR
CASE
YEAR(@enddate-1)
END
OR
CASE
YEAR(@enddate-2)
END
END
END