SQL 在 TSQL 中获取当前年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23963580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:57:46  来源:igfitidea点击:

Get current year in TSQL

sqltsqldatetime

提问by SBB

I have data I am trying to pull for a report and I am working on a Year to Date report. My columns in the table are formatted as datetime. I am trying to run a select statement to get all the results where date = this year.

我有我正在尝试为报告提取的数据,并且我正在处理年初至今的报告。我在表中的列格式为日期时间。我正在尝试运行一个选择语句来获取日期 = 今年的所有结果。

For example:

例如:

SELECT  A.[id], A.[classXML]
FROM   tuitionSubmissions as A
WHERE A.[status] = 'Approved' AND A.[reimbursementDate] = THISYEAR
FOR    XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');

Is there an eay way to acomplish this?

有没有简单的方法来完成这个?

回答by Justin Helgerson

Yes, it's remarkably easy in fact:

是的,事实上这非常容易:

WHERE YEAR(A.[reimbursementDate]) = YEAR(GETDATE())

回答by Jerrad

This should be a better way if performance is an issue (although it isn't as readable)

如果性能是一个问题,这应该是一个更好的方法(虽然它不那么可读)

where A.[reimbursementDate] between  
     DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) and
     DATEADD(MILLISECOND, -3, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))

Those funky DATEADD statements return the first and last days of the current year (through December 31 23:59:59.997). Since reimbursementDateisn't contained in a function, the query will be able to take advantage of any applicable indexes.

那些时髦的 DATEADD 语句返回当年的第一天和最后一天(截至 12 月 31 日 23:59:59.997)。由于reimbursementDate不包含在函数中,查询将能够利用任何适用的索引。