そのテーブル値関数を使用できます。
create function DateTable
(
@FirstDate datetime,
@LastDate datetime,
@handle nvarchar(10)='day',
@handleQuantity int=1
)
returns @datetable table (
[date] datetime
)
AS
begin
with CTE_DatesTable
as
(
select @FirstDate AS [date]
union ALL
select case @handle
when 'month' then dateadd(month, @handleQuantity, [date])
when 'year' then dateadd(year, @handleQuantity, [date])
when 'hour' then dateadd(hour, @handleQuantity, [date])
when 'minute' then dateadd(minute, @handleQuantity, [date])
when 'second' then dateadd(second, @handleQuantity, [date])
else dateadd(day, @handleQuantity, [date])
end
from CTE_DatesTable
where @LastDate >=
case @handle
when 'month' then dateadd(month, @handleQuantity, [date])
when 'year' then dateadd(year, @handleQuantity, [date])
when 'hour' then dateadd(hour, @handleQuantity, [date])
when 'minute' then dateadd(minute, @handleQuantity, [date])
when 'second' then dateadd(second, @handleQuantity, [date])
else DATEADD(day, @handleQuantity, [date])
end
)
insert @datetable ([date])
select [date] from CTE_DatesTable
option (MAXRECURSION 0)
return
end
次のように呼び出すことができます。
select [date],datepart(weekday,[date]) from dbo.DateTable('12/28/2005','12/30/2006',default,default)