我正在以下方案中处理日期操作。
输入:DateA,DateB,Month_count
前提条件:DateB始终大于DateA
Output:
1)I need to find newstartdate and newEndDate from DateB
newStartDate<DateA<newEndDate.
2)For newstartDate ,dateB is subtracted by month count .
3)NewEndDate is newStartDate+month_count.
4)Repeat 2,3 until the condition 1 becomes true.
我已经提出了执行此操作的条件。是否有任何方法可以简化此逻辑?
Declare @dateA datetime
Declare @dateB Datetime
declare @month_count int
declare @newstartdate datetime
declare @newenddate datetime
set @dateA= '2013-02-21'
set @dateB='2013-08-23'
set @month_count=3
SET @newstartdate=DATEADD(mm,-@month_count,@dateB)
Set @newenddate=DATEADD(mm,@month_count ,@newstartdate)
WHILE Not (@newstartdate < @dateA AND @dateA<@newenddate)
BEGIN
SET @newstartdate=DATEADD(mm,-@month_count,@newstartdate)
Set @newenddate=DATEADD(mm,@month_count,@newstartdate)
Select @dateA 'DateA',@newstartdate '@newstartdate',@newenddate '@newenddate'
END
答案 0 :(得分:1)
也许这样的事情有帮助吗?
declare @dateA datetime = '2013-02-21'
declare @dateB datetime = '2013-08-23'
declare @month_count int = 3
;with dates(newstartdate, newenddate)
as
(
SELECT DATEADD(month, -@month_count, @dateB)
,@dateB
UNION ALL
SELECT DATEADD(month, -@month_count, newstartdate)
,newstartdate
FROM dates
WHERE newstartdate > @dateA
)
SELECT TOP 1 *
FROM dates
ORDER BY newstartdate
答案 1 :(得分:0)
取决于你的意思简单。
我正在考虑如何使用递归CTE来做这件事,但Johan先到了那里。这可能是正确的做法。
然而,它并不一定像你所拥有的那样“简单”。你的可以进一步简化。
顺便说一句,我还建议你在SQL和变量中使用大写的方式保持一致。无论你选择什么样的风格,它都更容易阅读,如果它至少在内部一致,看起来“更好”。Declare @dateA datetime
Declare @dateB Datetime
declare @month_count int
declare @newstartdate datetime
declare @newenddate datetime
set @dateA= '2013-02-21'
set @dateB='2013-08-23'
set @month_count=3
Set @newenddate=@dateB
SET @newstartdate=DATEADD(mm,-@month_count,@dateB)
WHILE Not (@newstartdate < @dateA AND @dateA<@newenddate) BEGIN
Set @newenddate=@newstartdate
SET @newstartdate=DATEADD(mm,-@month_count,@newstartdate)
END
--do you need to select the interimediate results or simply the final?
Select @dateA 'DateA',@newstartdate '@newstartdate',@newenddate '@newenddate'