From SQL Server 2012, EOMENTH system function can be used for getting the last day of the month containing a specified date.
Before SQL Server 2012
Script
-- Before SQL Server 2012. DECLARE @DT VARCHAR(10); SET @DT = '2019-02-20'; SELECT DATEADD(d, -1, DATEADD(m, 1, CONVERT(DATE, LEFT(@DT, 8) + '01'))) AS 'the last day of the month', CONVERT(DATE, CONVERT(CHAR(8), @DT) + '01') AS 'the first day of the month' GO
Result
Using EOMONTH
Script
-- Using EOMONTH Function DECLARE @DT VARCHAR(10); SET @DT = '2019-02-20'; SELECT EOMONTH(@DT) AS 'the last day of the month', CONVERT(DATE, CONVERT(CHAR(8), @DT) + '01') AS 'the first day of the month' GO
Result
References
- EOMONTH (Transact-SQL): https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql?view=sql-server-ver15
No comments:
Post a Comment