Reputation: 11
I'm using varchar datatype for my StartDate and EndDate fields in SQL server 2005. The sample query is given here:
*I'm following dd/MM/yyyy format for date.
select * from dbo.SubDetails
where
((
DATEADD(DAY,DATEDIFF(DAY, 0, convert(datetime,StartDate,105)), 0) <=
DATEADD(DAY,DATEDIFF(DAY, 0, convert(datetime,'16/11/2012',105)), 0)
)
AND
(
DATEADD(DAY, DATEDIFF(DAY, 0, convert(datetime,EndDate,105)), 0) >=
DATEADD(DAY, DATEDIFF(DAY, 0, convert(datetime,'11/9/2012',105)), 0)
))
This query is giving me all records irrespective to records between date range. Any help would be appreciated. Thanks
Upvotes: 1
Views: 5929
Reputation: 117380
first of all - do not store date values in varchar columns, if you have to - use YYYYMMDD
format.
second - you can compare dates:
select *
from dbo.SubDetails
where
convert(datetime, StartDate, 105) <= convert(datetime,'16/11/2012', 105) and
convert(datetime, EndDate, 105) >= convert(datetime,'11/9/2012', 105)
Also, your query will return all data ranges intersecting given data range (11 Sep 2012 - 16 Nov 2012). Is that what you want to do?
update: If you need records where StartDate
and EndDate
between 9 Nov 2012 to 16 Nov 2012, you can do this (supposing that StartDate
<= EndDate
):
select *
from dbo.SubDetails
where
convert(datetime, StartDate, 105) >= convert(datetime,'09/11/2012', 105) and
convert(datetime, EndDate, 105) <= convert(datetime,'16/11/2012', 105)
Upvotes: 1