表里有一值为getdate()的DateTime数据类型字段ADDTIME, 现在需要查询该字段2006-4的数据这是我写的SQL:
select * from table where cast(addtime as varchar(50)) like '%2006-4%'
SQL语句正常,可数据取不到(确认是有数据的)又听别人说,CAST转换数据类型会有问题,要用FORMAT?
这个FORMAT怎么用?
select * from table where format(addtime,"YYYY-M") = '2006-4'  ???但SQL提示这不是一个函数,用不了的
实在不理解,请帮一下

解决方案 »

  1.   

    --查询时间不是这样的
    --查询2006-04
    select * from tablename 
    where datepart(year,shijianziduan)='2006' 
    and datepart(month,shijianziduan)='4'
      

  2.   

    --如此这般select * from table where convert(varchar(7),addtime,120)='2006-04'
      

  3.   

    select * from tablename 
    where convert(nvarchar(7),addtime,111)='2006/04'
      

  4.   

    SELECT * FROM tb WHERE DATEDIFF(mm,addtime,'2004-4' + '-1')=0
      

  5.   

    你执行下面的SQL语句看看结果,就知道你cast后的日期格式是不是YYYY-M:
    select cast(addtime as varchar(50)) as theDate from table
      

  6.   

    select * from table where ADDTIME>='2006-4-1' and ADDTIME<='2006-4-30'
      

  7.   

    select * from table where convert(varchar(7),addtime,120)='2006-04'
    个人认为这个不错