tags:

views:

89

answers:

3

Please help me to find out error in my SQL query. I have created this query to compare dates

select * from Joinplans jp
where cast(convert(varchar,GETDATE(),103) AS  datetime) BETWEEN    
    CASE(convert(varchar,jp.planstartDate,103) AS datetime) AND
    CASE(convert(varchar,DATEADD(DAY,jp.planDays,jp.planstartDate),103) AS DATETIME)

It's giving me the error:

incorrect near 'AS'

I am using SQL Server 2005.

+3  A: 

You wrote case instead of cast in two instances.

Marcelo Cantos
ohh.. thanks .. plez tell me is it good way to compare dates in this way or if not than what is good way to compare dates in such a situation
Rajesh Rolen- DotNet Developer
still giving me error:The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Rajesh Rolen- DotNet Developer
+1  A: 

If planStartDate is actually a date, then there is no need to cast it to a character column:

Select ...
From Joinplans jp 
where GetDate() Between planStartDate And DateAdd(day, jp.planDays, jp.planStartDate)

Now, if planStartDate is storing both date and time data, then you might want to use something like:

Select ...
From Joinplans jp 
Where planStartDate <= GetDate()  
    And GetDate() < DateAdd(day, jp.planDays + 1, jp.planStartDate)

This ensures that all times on the last date calculated via the DateAdd function are included

Thomas
datatype of planstartdate is smalldatetime and i am storing datetime value in which time is 00:00
Rajesh Rolen- DotNet Developer
but as getdate() contains time part also.. than its creates problem (not proper result)
Rajesh Rolen- DotNet Developer
It might with the start date only which I've corrected.
Thomas
A: 

select * from Joinplans jp where CONVERT(VARCHAR(10),GETDATE(),23) BETWEEN
CONVERT(VARCHAR(10),jp.planstartDate,23) AND CONVERT(VARCHAR(10),DATEADD(DAY,jp.planDays,jp.planstartDate),23)

Yaqub Ahmad