我有开始日期&将Mdate作为表中的列,我想在SQL中执行类似下面的操作
将1个月添加到Start_Date,直到开始日期> Mdate
我尝试使用while和if概念,但没有运气。
DECLARE @MIGRATIONDATE DATE, @STRT_DATE DATE, @NEXTD DATE
SET @MIGRATIONDATE =20140725
SET @STRT_DATE = 20140521
SELECT WHILE ( @STRT_DATE > @MIGRATIONDATE)
BEGIN
DATEADD(MM,1,@STRT_DATE))
END
感谢你能指导我吗?
答案 0 :(得分:1)
select
case when start_date<Mdate then dateadd(mm,1,start_date) else start_date end
from yourTable
假设start_date是20140721而MigrationDate是20140525然后它返回给你接受的结果
select case
when convert( date,'20140721') <convert(date,'20140525')
then dateadd(mm,1,'20140721') else '20140721' end
答案 1 :(得分:0)
我不知道你是否想获得该表的一行。如果你想为每一行做,那么你应该将它包装在一个函数中并使用CROSS APPLY。
declare
@startdate datetime,
@enddate datetime
set @startdate = '20140101'
set @enddate = '20150101'
;WITH date_range (thedate) AS (
select @startdate
UNION ALL SELECT DATEADD(MONTH, 1, thedate)
FROM date_range
WHERE DATEADD(MONTH, 1, thedate) <= @enddate
)
SELECT thedate FROM date_range
如果你想要一个功能:
CREATE FUNCTION [dbo].[ExplodeDates](@startdate datetime, @enddate datetime)
returns table as
return (
WITH date_range (thedate) AS (
select @startdate
UNION ALL SELECT DATEADD(DAY, 1, thedate)
FROM date_range
WHERE DATEADD(DAY, 1, thedate) <= @enddate
)
SELECT thedate FROM date_range
);
SELECT Id,thedate
FROM Table1 T1
CROSS APPLY [dbo].[ExplodeDates](T1.StartDate,T1.EndDate)
答案 2 :(得分:0)
如何(SQL Fiddle):
SELECT DATEADD(month,
DATEDIFF(month, Start_Date, Mdate) + 1,
Start_Date) AS NEW_START_DATE
FROM MyTable;
如果Start_Date有可能大于或等于Mdate,请使用以下(SQL Fiddle):
SELECT Start_Date AS OLD_START_DATE,
CASE WHEN DATEDIFF(month, Start_Date, Mdate) > 0
THEN DATEADD(month, DATEDIFF(month, Start_Date, Mdate) + 1, Start_Date)
ELSE Start_Date END AS NEW_START_DATE,
Mdate
FROM MyTable;