您好我在SqlServer 2008中写了这个查询 但有些事情出了问题
select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, NewsDate) , convert(datetime,@Todaydate )) <= @Count)
@NewsDate
和@Todaydate
是两个nvarchar参数,保存方式如下2014/11/16
运行此查询会给我一个错误:
Conversion failed when converting date and/or time from character string
答案 0 :(得分:2)
尝试将正确的样式参数添加到转换函数中(请参阅MSDN:link)
即CONVERT(DATETIME, NewsDate, 111)
(111是YYYY / MM / DD的样式)
然后你得到:
SELECT *
FROM News_Table
WHERE (DATEDIFF( DAY ,
CONVERT(DATETIME, NewsDate, 111) ,
CONVERT(DATETIME,@Todaydate, 111)
) <= @Count)
答案 1 :(得分:1)
了解更多click here
SELECT convert(datetime, '2014/11/16', 111) as datetime
<强> OP 强>
所以你的查询就像这样
Select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, '2014/11/16', 111) , convert(datetime,@Todaydate,111 )) <= @Count)
答案 2 :(得分:1)
使用Convert(datetime, @yourvalue, 111)
select * from News_Table
where (DATEDIFF( DAY ,convert(datetime, @NewsDate, 111) , convert(datetime,@Todaydate, 111 )) <= @Count)
答案 3 :(得分:0)
试试这个
SELECT *
FROM News_Table
WHERE (DATEDIFF(DAY,CAST(NewsDate AS Datetime),CAST(@Todaydate AS Datetime)) <= @Count)
答案 4 :(得分:0)
您需要执行类似的操作才能将该字符串转换为DATETIME数据类型
DECLARE @Date NVARCHAR(20) = '2013/11/16'
SELECT CAST((LEFT(@Date, 4) + SUBSTRING(@Date, 6 ,2) + RIGHT(@Date, 2)) AS DATETIME)
查询
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)
注意强>
如果变量@Todaydate
实际上存储了今天的日期,那么为什么不使用简单的GETDATE()
函数。