Get current year in TSQL

匆匆过客 提交于 2020-06-10 07:31:53

问题


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?


回答1:


Yes, it's remarkably easy in fact:

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



回答2:


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 reimbursementDate isn't contained in a function, the query will be able to take advantage of any applicable indexes.



来源:https://stackoverflow.com/questions/23963580/get-current-year-in-tsql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!