繁体   English   中英

如果该月不存在该日期,如何更改 SQL Server 中的日期并设置该月的最后一天

[英]How to change day of date in SQL server and set last day of month if the day does not exist in the month

我试过用这个

dateadd(month, 0, dateadd(day,(30-datepart(dd,'2015-02-28')),'2015-02-28'))

为了获得所需的输出,而不是获得'2015-02-28',我得到'2015-03-02'。 如果月份中不存在日期,如何更改 SQL 中的日期并设置月份的最后一天?

====使用样本数据更新 ============

注意:目标不是获取本月的最后一天

如果我想将日期更改为 30 并且它是一个只有 28 天的月份。 它应该是月末日期。 如果不是日期应该是 30 号。

将日期更改为 30 日 如果二月应该是 - '2015-02-28' 如果三月应该是 - '2015-03-30' 如果四月应该是 - '2015-04-30'

如果您的 sql server 版本是 2012 或更高版本,则存在此功能

SELECT EOMONTH('2015-02-15')

返回2015-02-28

对于 sql server 2012 或更高版本,请查看 HoneyBadger 的回答。 对于旧版本:

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@mydate)+1,0))
-- Replace Day portion of @OrigDate with @NewDay.
-- If the result would be beyond the end of the month, return the last day of the month

create function ReplaceDay ( @OrigDate date, @NewDay int ) 
returns date
as 
begin

declare @NewDate date

-- Deal with extreme cases, in case someone passes @NewDay = 7777 or @NewDay = -7777

if @NewDay < 1
  set @NewDay = 1

if @NewDay > 31 
  set @NewDay = 31

-- Subtract the DAY part of the original date from the new day.
-- Add that many days to the original date

-- Example:  if the original date is 2018-02-08 and you want to replace 08 with 17, then add 17-08=9 days

set @NewDate = DateAdd ( d, @NewDay-Day(@OrigDate), @OrigDate )

-- Have we ended up in the next month? 
-- If so subtract days so that we end up back in the original month.
-- The number of days to subtract is just the Day portion of the new date.

-- Example, if the result is 2018-03-02, then subtract 2 days

if Month(@NewDate)<>Month(@OrigDate)
  set @NewDate = DateAdd ( d, -Day(@NewDate), @NewDate )

return @NewDate

end

go

select dbo.ReplaceDay ( '2017-02-08', 17 ) -- Returns 2017-02-17 

select dbo.ReplaceDay ( '2017-02-08', 30 ) -- Returns 2017-02-28

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM