TSQL retrieve all records in current month/year

后端 未结 2 1947
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 23:06

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:40

    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!)

提交回复
热议问题