Click here to Skip to main content
15,918,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I want to check a particular date between two datetime values.

For Example
if
C#
startdate = 2012-04-23 00:00:00.000
enddate = 2012-04-26 00:00:00.000


i am using this querry-


C#
select leaveemployeeid from leave where '23/04/2012' between convert(VARCHAR, startdate, 103) and convert(VARCHAR, enddate, 103);



it works fine.

but if enddate is to next month from startdate then this querry return null.

for example


C#
startdate = 2012-04-23 00:00:00.000
enddate = 2012-05-04 00:00:00.000


querry return null.

Thanks in Advance.
Posted

This may happen because by converting the dates to varchar you are doing a string comparision. Try this by not converting the dates to varchar.

[Edit]
something like this
SQL
select leaveemployeeid from leave where convert(datetime,'23/04/2012') between convert(datetime,'2012-04-23 00:00:00.000') and convert(datetime,'2012-05-04 00:00:00.000')
or
select leaveemployeeid from leave where convert(datetime,'23/04/2012') between startdate  and enddate 
-- where startdate and enddate are date fields.

[/Edit]
 
Share this answer
 
v2
Comments
mayankshrivastava 26-Apr-12 4:27am    
gives the following error-
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
deeptibansal 26-Apr-12 5:17am    
Try this:

select leaveemployeeid from leave where
where convert(datetime,'23/04/2012',103)
between convert(datetime,'2012-23-04 00:00:00.000',103) and
convert(datetime,'2012-04-05 00:00:00.000',103)
mayankshrivastava 27-Apr-12 2:12am    
It works Fine.
Thanks DEEPTI :)
deeptibansal 27-Apr-12 3:11am    
:)
If you want to use between operator to compare date, in end date you will have to set maximum time.
Like enddate = 2012-05-04 23:59:59.999
 
Share this answer
 
You should always use parameterized query. It not just avoid SQL Injection attack, but also maintains code clean and easy.

Try:
SQL
DECLARE @leaveDate DateTime
@leaveDate = '23/04/2012'
select leaveemployeeid from leave where @leaveDate between startdate and enddate
 
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