在 SQL 中获取一个月的最后一天

问题描述:

我需要获取在 SQL 中作为日期给出的月份的最后一天.如果我有一个月的第一天,我可以这样做:

I need to get the last day of the month given as a date in SQL. If I have the first day of the month, I can do something like this:

DATEADD(DAY, DATEADD(MONTH,'2009-05-01',1), -1)

但是有谁知道如何概括它以便我可以找到任何给定日期的该月的最后一天?

But does anyone know how to generalize it so I can find the last day of the month for any given date?

这是我的版本.不需要字符串操作或转换,只需对 DATEADDYEARMONTH 函数各调用一次:

Here's my version. No string manipulation or casting required, just one call each to the DATEADD, YEAR and MONTH functions:

DECLARE @test DATETIME
SET @test = GETDATE()  -- or any other date

SELECT DATEADD(month, ((YEAR(@test) - 1900) * 12) + MONTH(@test), -1)