【问题标题】:How to change day of date in SQL server and set last day of month if the day does not exist in the month如果该日期不存在,如何在 SQL Server 中更改日期并设置月份的最后一天
【发布时间】:2018-03-07 09:27:07
【问题描述】:

我试过用这个

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'

【问题讨论】:

  • 你的意思是上个月的最后一天?请详细说明您的问题并添加一些示例数据
  • 你的问题还不清楚。请edit 将示例数据添加为 DDL+DML 和所需结果。
  • 看起来您需要一个函数来替换日期的 DAY 部分。我的回答有帮助吗?
  • 是的。谢谢

标签: sql sql-server


【解决方案1】:

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

SELECT EOMONTH('2015-02-15')

返回2015-02-28

【讨论】:

  • 您可以通过为较旧的 sql server 版本添加以下内容来完成您的答案:SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@mydate)+1,0))
  • @B3S,请随时添加作为答案。
  • 感谢您的回答,但实际上这是我想要实现的其他目标。我已经用示例数据更新了我的问题以供参考。抱歉,我之前没有提供。
【解决方案2】:
-- 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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多