TSQL retrieve all records in current month/year

后端 未结 2 1898
野性不改
野性不改 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!)

提交回复
热议问题