简体   繁体   中英

converting varchar to date - SQL Server

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM