Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current year in TSQL

Tags:

sql

datetime

tsql

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?

like image 534
SBB Avatar asked May 30 '14 21:05

SBB


People also ask

How do I get the current year in SQL query?

The YEAR() function returns the year part for a given date (a number from 1000 to 9999).

How do I get current year and month in SQL?

Just run these SQL queries one by one to get the specific element of your current date/time: Current year: SELECT date_part('year', (SELECT current_timestamp)); Current month: SELECT date_part('month', (SELECT current_timestamp)); Current day: SELECT date_part('day', (SELECT current_timestamp));

How do I get the current year in SSMS?

SQL Server YEAR() Function The YEAR() function returns the year part for a specified date.


2 Answers

Yes, it's remarkably easy in fact:

WHERE YEAR(A.[reimbursementDate]) = YEAR(GETDATE()) 
like image 116
Justin Helgerson Avatar answered Sep 24 '22 04:09

Justin Helgerson


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.

like image 30
Jerrad Avatar answered Sep 24 '22 04:09

Jerrad