Click here to Skip to main content
15,885,669 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In my Table valued function, I have a variable of type date. I need to compare it (in a where clause) with the values of a column in a table, whose type is datetime2. Can anyone please help me with this, as the cast is not working for me.

What I have tried:

Following is my code:

SQL
select * from table1 where [Date1] >= cast(@Todate as datetime2)


Here, [Date1] is a column in table1 of type datetime2 and @Todate is of type date.
Posted
Updated 16-May-16 7:48am
v2
Comments
Tomas Takac 16-May-16 5:12am    
What does it mean "the cast is not working for me"?
Bhavika Mdm 16-May-16 5:16am    
I mean, when I try to execute the above query, I don't get any result, where as, I have many values for [Date1] that is greater then @Todate.
Simon_Whale 16-May-16 5:47am    
can you show some example of what you mean by not working?
Bhavika Mdm 16-May-16 6:05am    
I got the solution. The issue was that, the date part was getting converted to datetime2, but with time as 00:00:00. Then I did in the following way, and it worked.

select *
from Table1
where [Date1] >= DATEADD(MS,-1,CAST(DATEADD(DD,1,@toDate) AS datetime2))

1 solution

OK, OP already has found solution:
Quote:
I got the solution. The issue was that, the date part was getting converted to datetime2, but with time as 00:00:00. Then I did in the following way, and it worked.

SQL
select *
from Table1
where [Date1] >= DATEADD(MS,-1,CAST(DATEADD(DD,1,@toDate) AS datetime2))


But i have to point out that - as MSDN documentation[^] states - an implicit conversion between date and datetime2 data types is possible by using CAST and CONVERT functions.

A datetime2 (Transact-SQL)[^] data type is well known as an extension of the existing datetime (Transact-SQL)[^] type that has a larger date range, a larger default fractional precision, and optional user-specified precision, but date[^] data type represents date without time part. So, the result of implicit conversion from date to datetime2 is date with time equal to zero!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900