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

时间:2018-03-07 09:27:08

标签: sql sql-server

我尝试使用此

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'

3 个答案:

答案 0 :(得分:1)

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

SELECT EOMONTH('2015-02-15')

返回2015-02-28

答案 1 :(得分:0)

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

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@mydate)+1,0))

答案 2 :(得分: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