SQL:如何生成给定月份和日期的下一个日期

Jus*_*anz 5 sql

在我的表中,我有一个月(tinyint)和一天(tinyint)字段.我希望有一个功能,可以在这个月和日期生成这个月和日的下一个日期(包括年份)的日期时间.

因此,如果我有月= 9,日= 7它将产生9/7/2009.
如果我有第1个月,第1天将产生1/1/2010.

Pet*_*hia 2

像这样的东西会起作用。它是您方法的变体,但它不使用 MM/DD/YYYY 文字格式,并且不会因错误输入而崩溃(无论好坏)。

declare @month tinyint
declare @day tinyint
set @month = 9
set @day = 1

declare @date datetime

-- this could be inlined if desired
set @date = convert(char(4),year(getdate()))+'0101'
set @date = dateadd(month,@month-1,@date)
set @date = dateadd(day,@day-1,@date)

if @date <= getdate()-1
  set @date = dateadd(year,1,@date)

select @date
Run Code Online (Sandbox Code Playgroud)

或者,要创建 YYYYMMDD 格式的字符串:

set @date = 
  right('0000'+convert(char(4),year(getdate())),4)
+ right('00'+convert(char(2),@month),2)
+ right('00'+convert(char(2),@day),2)
Run Code Online (Sandbox Code Playgroud)

另一种方法可以避免使用文字:

declare @month tinyint
declare @day tinyint
set @month = 6
set @day = 24

declare @date datetime
declare @today datetime

-- get todays date, stripping out the hours and minutes
-- and save the value for later
set @date = floor(convert(float,getdate()))
set @today = @date

-- add the appropriate number of months and days
set @date = dateadd(month,@month-month(@date),@date)
set @date = dateadd(day,@day-day(@date),@date)

-- increment year by 1 if necessary
if @date < @today set @date = dateadd(year,1,@date)

select @date
Run Code Online (Sandbox Code Playgroud)