TSQL检索当前月/年的所有记录 [英] TSQL retrieve all records in current month/year

查看:178
本文介绍了TSQL检索当前月/年的所有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datetime字段叫做DateFinished。我需要能够检索DateFinished在当前月/年之内的所有记录。

解决方案

如果您只有少数行,则可以将所有行都 DateFinished 在今年的这个月。

  SELECT * 
FROM MyTable
WHERE年(DateFinished)=年(CURRENT_TIMESTAMP)
和月(DateFinished)=月(CURRENT_TIMESTAMP)

尽管如此,这可能会相当慢 - 在这种情况下,使用 DateAdd DatePart BETWEEN 可能更合适,可以利用索引(我没有时间写出一个涉及到的答案!)


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.

解决方案

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

这篇关于TSQL检索当前月/年的所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆