SQL SQL查询以查找当月的最后一天?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7429885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:07:58  来源:igfitidea点击:

SQL query to find last day of current month?

sqlsql-server-2008

提问by Ajendra Prasad

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
 LastDay_CurrentMonth

Hi everyone I have a query to find the last day of current month, which is surely working well, but I am unable to understand it, because I have other similar requirements and have to change it accordingly.

大家好,我有一个查询要找到当月的最后一天,这肯定工作得很好,但我无法理解,因为我有其他类似的要求,必须相应地更改它。

Can somebody explain it to me.. Thanks in advance

有人可以向我解释一下..提前致谢

回答by Mikael Eriksson

Get the DateTime of Now

获取现在的日期时间

GETDATE() -- 2011-09-15 13:45:00.923

Calculate the difference in month's from '1900-01-01'

计算与“1900-01-01”的月份差异

DATEDIFF(m, 0, GETDATE()) -- 1340

Add the difference to '1900-01-01' plus one extra month

将差额加到“1900-01-01”加上一个月

DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0) -- 2011-10-01 00:00:00.000

Remove one second

删除一秒钟

DATEADD(s, -1, DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0)) -- 2011-09-30 23:59:59.000

回答by FistOfFury

This will give you the last day of current month but ignores time

这会给你当月的最后一天,但忽略时间

select EOMONTH(GETDATE())

选择 EOMONTH(GETDATE())

From Microsoft tech net

来自微软技术网

回答by AlejandroR

CREATE FUNCTION  EOMONTH
(
    @date datetime,
    @months int
)
RETURNS datetime
AS
BEGIN
     declare @eom datetime
     declare @d datetime
     set @d = dateadd(MONTH, @months, @date)
     select @eom =   dateadd(SECOND,-1,DATEADD(MONTH,datediff(MONTH,0,@d)+1,0))
    RETURN  @eom 

END
GO