Question

hi i wrote this query in SqlServer 2008 but some thing goes wrong

select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, NewsDate) , convert(datetime,@Todaydate )) <= @Count)

that @NewsDate and @Todaydate are two nvarchar parameters that are saved like this 2014/11/16

running this query give me an error:

Conversion failed when converting date and/or time from character string
Was it helpful?

Solution

Try adding the correct style parameter to your convert function (see MSDN: link )

ie CONVERT(DATETIME, NewsDate, 111) (111 is the style for YYYY/MM/DD)

Then you get:

SELECT * 
FROM  News_Table
WHERE (DATEDIFF( DAY ,
                 CONVERT(DATETIME, NewsDate, 111) , 
                 CONVERT(DATETIME,@Todaydate, 111)
               ) <= @Count)

OTHER TIPS

use Convert(datetime, @yourvalue, 111)

select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, @NewsDate, 111) , convert(datetime,@Todaydate, 111 )) <= @Count)

http://www.sqlusa.com/bestpractices/datetimeconversion/

To know more click here

SELECT convert(datetime, '2014/11/16', 111) as datetime

OP

enter image description here

So your query would be like this

Select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, '2014/11/16', 111) , convert(datetime,@Todaydate,111 )) <= @Count)

Try like this

SELECT * 
FROM News_Table
WHERE (DATEDIFF(DAY,CAST(NewsDate AS Datetime),CAST(@Todaydate AS Datetime)) <= @Count)

You will need to do something like this to convert that string into DATETIME datatype

DECLARE @Date NVARCHAR(20) = '2013/11/16'

SELECT CAST((LEFT(@Date, 4) + SUBSTRING(@Date, 6 ,2) + RIGHT(@Date, 2)) AS DATETIME)

for your query

select * from News_Table
where (DATEDIFF( DAY , CAST((LEFT(NewsDate, 4) + SUBSTRING(NewsDate, 6 ,2) + RIGHT(NewsDate, 2)) AS DATETIME)
                     , CAST((LEFT(@Todaydate, 4) + SUBSTRING(@Todaydate, 6 ,2) + RIGHT(@Todaydate, 2)) AS DATETIME)
                ) <= @Count)

Note

If variable @Todaydate is actually storing today's date then why not use simply GETDATE() function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top