在 SQL 中获取一个月的最后一天 [英] Get the last day of the month in SQL
本文介绍了在 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?
推荐答案
这是我的版本.不需要字符串操作或转换,只需对 DATEADD
、YEAR
和 MONTH
函数各调用一次:
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)
这篇关于在 SQL 中获取一个月的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文