表里面的数据是很多年的数据了,要求每次运行时自动查找出当前月的数据。例如表A:ID    Name     Date
1     AAA      2009-1-1
2     BBB      2010-1-1
3     CCC      2010-1-10因为现在是2010年1月份,所以查询到的结果应该为:
2     BBB      2010-1-1
3     CCC      2010-1-10我现在的做法是
select * from 表A WHERE (((Month([Date]))=Month(Date())) AND ((Year([Date]))=Year(Date())));
就是根据Date字段来判断它的年是否等于现在日期的年,月是否等于现在日期的月。我想请教下大家除了这种方法还有没有其它更灵活简便的方法?

解决方案 »

  1.   

    select * from 表A 
    where datediff(month,Date,getdate())=0
      

  2.   

    if not object_id('ta') is null
    drop table ta
    Go
    Create table ta([ID] int,[Name] nvarchar(3),[Date] Datetime)
    Insert ta
    select 1,N'AAA','2009-1-1' union all
    select 2,N'BBB','2010-1-1' union all
    select 3,N'CCC','2010-1-10'
    Go
    select * from ta 
    where datediff(month,Date,getdate())=0
    /*
    ID          Name Date
    ----------- ---- -----------------------
    2           BBB  2010-01-01 00:00:00.000
    3           CCC  2010-01-10 00:00:00.000(2 個資料列受到影響)
    */
      

  3.   


    select * from tb
    where datediff(month,Date,getdate()) = 0
      

  4.   

    晕,datediff,我怎么把这个忘记了呢,用了几次了,但是每次到用的时候还是想不起来它。
    感谢大家啊!
      

  5.   


    datediff(mm,Date,getdate())=0