SQL Last Day of Month

How do I get the last day of the month in a SQL query? Well it turns out that the release of SQL Server 2012 marks the release of the EOMONTH() function.

Prior to SQL Server 2012, this is what typical T-SQL to compute last day of the month would look like:

DECLARE @date DATE = '2017-12-15';
DECLARE @firstOfMonth DATE = DATEFROMPARTS(YEAR(@date), MONTH(@date), 1);
SELECT DATEADD(DAY,-1, DATEADD(MONTH, 1, @firstOfMonth));

With SQL Server 2012 or later, the EOMONTH() gives you a much more concise option which looks like:

DECLARE @date DATE = '2017-12-15';
SELECT EOMONTH(@date)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s