SQL SELECT 每月的第一天和最后一天。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28433449/
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 03:16:19  来源:igfitidea点击:

SQL SELECT First Day and Last Day of the Month.

sqlsql-servertsqldatetime

提问by NCollinsTE

Dearest professionals,

最亲爱的专业人士,

I have a query built to get the first and last day of the current month, but I'm having an issue with the time stamp for the First Day of the month.

我有一个查询来获取当月的第一天和最后一天,但是我遇到了当月第一天的时间戳问题。

declare @FirstDOM datetime, @LastDOM datetime

set @FirstDOM = (select dateadd(dd,-(day(getdate())-1),getdate()) )
set @LastDOM = (select dateadd(s,-1,dateadd(mm,datediff(m,0,getdate())+1,0))) 

Since it's February of 2015, I would like to get results of:

由于是 2015 年 2 月,我想得到以下结果:

@FirstDOM = 2015-02-01 00:00:00.000
@LastDOM = 2015-02-28 23:59:59.000

@LastDOM is correct, but I'm not getting the zeroes for the time stamp portion of @FirstDOM, I'm getting the correct date, but the time of the time I run the script. Say it's 8:50 a.m., I get:

@LastDOM 是正确的,但我没有得到@FirstDOM 的时间戳部分的零,我得到了正确的日期,但是我运行脚本的时间。假设现在是上午 8:50,我得到:

2015-02-01 08:50:49.160

What is the best way to fix this little snafu?

解决这个小麻烦的最佳方法是什么?

Regards,

问候,

Nick

缺口

回答by Suraj Singh

declare @FirstDOM datetime, @LastDOM datetime

set @FirstDOM = (select dateadd(d,-1,dateadd(mm,datediff(m,0,getdate()),1 )))
set @LastDOM = (select dateadd(s,-1,dateadd(mm,datediff(m,0,getdate())+1,0))) 
Print @FirstDOM
Print @LastDOM

回答by Swapnil

Convert @FirstDOM to DATEas below:

将@FirstDOM 转换DATE为如下:

declare @FirstDOM datetime, @LastDOM datetime

set @FirstDOM = (select CONVERT(DATE,dateadd(dd,-(day(getdate())-1),getdate())) )
set @LastDOM = (select dateadd(s,-1,dateadd(mm,datediff(m,0,getdate())+1,0))) 
SELECT @FirstDOM,@LastDOM

I hope this will help!

我希望这个能帮上忙!

Thanks,

谢谢,

Swapnil

交换尼

回答by Bamidelzz

You can get the First and Last Day of the month using this:

您可以使用以下方法获取本月的第一天和最后一天:

SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)  ----First Day
SELECT DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)) ----Last Day

回答by Joe Platano

in addition to other answers, since SQL-Server 2012, Microsoft offers

除了其他答案之外,自 SQL-Server 2012 起,Microsoft 提供

EOMONTH ( start_date [, month_to_add ] )  

More details on msdn

有关msdn 的更多详细信息

--

——

of topic: I stumbled on this question looking for First Day of Month in SQL which has been answered by others

主题:我偶然发现了这个问题,在 SQL 中寻找已被其他人回答的 First Day of Month