SQLServerでストアドプロシージャ (stored procedure) を使って指定月の月初から月末までの日を取得する必要があったので作成しました。
ストアドプロシージャでカレンダーを作成する
SQLServerでストアドプロシージャ (stored procedure) を使って指定月の月初から月末までの日を取得する必要があったので作成しました。
カレンダー作成ストアドプロシージャ
作成したストアドプロシージャ (stored procedure) は以下の通りです。
CREATE Procedure [dbo].[指定月のカレンダー]
(
@YearMonth as varchar(6)
)
AS
Declare @from datetime
Declare @to datetime
Declare @nowDate datetime
Declare @workDate table([makeDate] [datetime]);
— 指定の年月の1日をfromに
Set @from = cast( @YearMonth + ’01’ as datetime )
— 指定の年月の翌月から1日引いた日(月末)を@toに
Set @to = dateadd( day, -1, dateadd( month, 1, @from ))
SELECT @nowDate = @from
WHILE ( @nowDate >= @from and @nowDate <= @to )
BEGIN
INSERT INTO @workDate VALUES ( @nowDate )
SELECT @nowDate = dateadd( day, 1, @nowDate )
END
SELECT CONVERT( VARCHAR, makeDate, 112 ) AS days from @workDate order by makeDate
[/sql]
ストアドプロシージャ (stored procedure) の呼び出しは以下の通りです。
[text]
exec 指定月のカレンダー @YearMonth='201301'
[/text]
カレンダー作成ストアドプロシージャ実行結果
実行結果は
20130101
20130102
20130103
20130104
20130105
20130106
20130107
20130108
20130109
20130110
20130111
20130112
20130113
20130114
20130115
20130116
20130117
20130118
20130119
20130120
20130121
20130122
20130123
20130124
20130125
20130126
20130127
20130128
20130129
20130130
20130131
ちなみに2月でも
exec 指定月のカレンダー @YearMonth='201302'
20130201
20130202
20130203
20130204
20130205
20130206
20130207
20130208
20130209
20130210
20130211
20130212
20130213
20130214
20130215
20130216
20130217
20130218
20130219
20130220
20130221
20130222
20130223
20130224
20130225
20130226
20130227
20130228
で大丈夫です。
