Is there a quicker and easier to read way in order to get the last day of the previous month in T-SQL?
I have found this piece of source code, which does the trick, but looks obfuscated unless properly previously commented:
-- Declar variabila pentru ultima zi din luna anterioară.
DECLARE @DSL [DATETIME]
SET @DSL = (SELECT DATEADD( dd
, 0
, DATEDIFF( dd
, 0
, DATEADD( s
, -1
, DATEADD( mm
, DATEDIFF( m
, 0
, GETDATE())
, 0)))))
PRINT 'Declar variabila pentru ultima zi din luna anterioară.'
PRINT @DSL
The message window with the results show the following output:
Declar variabila pentru ultima zi din luna anterioară.
Mar 31 2015 12:00AM
Please forgive my ignorance, I feel like a new-born newbie when I see these tricks.
SELECT @@VERSION
reports:
Microsoft SQL Server 2008 (SP2) – 10.0.4000.0 (Intel X86)
Sep 16 2010 20:09:22
Copyright (c) 1988-2008 Microsoft Corporation
Express Edition with Advanced Services on Windows NT 5.1 (Build 2600: Service Pack 3)
Best Answer
This one works in SQL Server 2008 R2, will probably work on SQL Server 2008 too :