TSQL retrieve all records in current month/year

后端 未结 2 1899
野性不改
野性不改 2021-02-08 22:58

I have a datetime field called DateFinished. I need to be able to retrieve all records in which DateFinished is within the current month/year.

相关标签:
2条回答
  • 2021-02-08 23:42

    If you've only got a small number of rows, this will do to get all rows where DateFinished is in this month of this year.

    SELECT * 
    FROM MyTable
    WHERE Year(DateFinished) = Year(CURRENT_TIMESTAMP) 
                     AND Month(DateFinished) = Month(CURRENT_TIMESTAMP)
    

    This could get quite slow over a large number of rows though - in which case using DateAdd, DatePart and BETWEEN is probably more appropriate, and can take advantage of indexes (I don't have time to write an answer involving those right now!)

    0 讨论(0)
  • 2021-02-08 23:54

    Just as an alternative - this should use an index on DateFinished.

    SELECT * 
    FROM MyTable
    WHERE DateFinished BETWEEN 
         DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
         AND 
         DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)
    
    0 讨论(0)
提交回复
热议问题