Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi ,
How do i select the Data's between the two date's

SQL
declare @fromdate Datetime,@todate datetime,@sql nvarchar(max) ;
select @fromdate ='2013/05/01'
select @todate='2014/05/31'
select @adv_id='4'
set @sql= N'';
set @sql += N' select *from table where paid_date between '+@fromdate+' and '+@todate+''
print @sql
EXEC sp_executesql @sql;



but it says

SQL
Conversion failed when converting date and/or time from character string.
Posted
Updated 18-Jun-14 8:28am
v2

1 solution

SQL
set @sql += N' select *from table where paid_date between '+@fromdate+' and '+@todate+''

This line forces SQL to convert between types (it contains different types: string and datetime). As you didn't specified how to do that convert SQL goes by the last parameter on the line, which is type of datetime! You have explicitly convert datetime variables to string...
SQL
set @sql += N' select *from table where paid_date between '''+convert(nvarchar, @fromdate, 103)+''' and '''+convert(nvarchar, @todate, 103)+''''

Also notice the quotes! It ensures that the date-strings created by CONVERT will be treated as string (enclosed by quotes)
 
Share this answer
 
Comments
King Fisher 18-Jun-14 9:24am    
thank you for Reply,
it says "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."

and i changed into
select *from table where convert(nvarchar,paid_date,103) between '''+convert(nvarchar, @fromdate, 103)+''' and '''+convert(nvarchar, @todate, 103)+''''

but it doesn't filter any records ,it shows all those values from table. :(

my column datatype is Datetime.
Kornfeld Eliyahu Peter 18-Jun-14 9:28am    
Probably 103 is not your code... Check help for CONVERT to pick the right number
(the number represents a datetime format)
By the way why to use dynamic sql? If you have not you need not - your life will be much better without...
King Fisher 18-Jun-14 9:32am    
kind of task sir, :)
King Fisher 19-Jun-14 0:26am    
i used 102 format. its worked.thanks :)
Kornfeld Eliyahu Peter 19-Jun-14 2:16am    
Glad to help!

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