再帰的CTEを使用できます
;with cte(intCount,myDate)
as
(
Select 1, CONVERT(VARCHAR(25),DATEADD(m, 1,
DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),101)
union all
Select intCount+1 ,CONVERT(VARCHAR(25),DATEADD(m,-(intCount-1),
DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),101) from cte
where intCount<=24
)
Select myDate from cte
更新しました:
必要に応じて、テーブル変数または一時テーブルに保存できます
Declare @Date table
(myDate varchar(25))
Declare @count int
set @count=24
;with cte(intCount,myDate)
as
(
Select @count-1, CONVERT(VARCHAR(25),DATEADD(m,-(@count-1),
DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),101)
union all
Select intCount-1 ,CONVERT(VARCHAR(25),DATEADD(m,-(intCount-1),
DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),101) from cte
where intCount>0
)
Insert into @Date(myDate)
Select myDate from cte
または、関数を作成できます
go
alter FUNCTION FnGetDate(@intCount int)
RETURNS @rtnTable TABLE
(
myDate varchar(25)NOT NULL
)
AS
BEGIN
;with cte(level,myDate)
as
(
Select @intCount-1, CONVERT(VARCHAR(25),DATEADD(m,-(@intCount-1),
DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),101)
union all
Select level-1 ,CONVERT(VARCHAR(25),DATEADD(m,-(level-1),
DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),101) from cte
where level>0
)
Insert into @rtnTable(myDate)
select myDate from cte
return
END
今、あなたはあなたの機能を次のようにすることができます
Select * from dbo.FnGetDate(24)