2

ランダムに終了するcursurに問題があります。要素ごとに行を作成したいので、要素ごとに2012年の毎月の行があります。特定の月に行が欠落している場合は、それも作成する必要があります。

現在、2057年まで毎月最後の要素の行を生成しています。

これで、2057年までの毎月まで、各要素の行があり、テーブル内の1つの要素のみがあります。

私のテーブルデザイン:

create table tblDataUpdateTest
(
slno int identity(1,1),
cName varchar(50),
cRemarks varchar(50),
[Date] date,
 )

insert into tblDataUpdateTest (cName, cRemarks,[Date]) values ('name1','Text1','2012-01-01'),
('name2','Text2','2012-01-01')

私のコード:

declare @y as int
declare @d as int
SET @y = 2012
SET @d = 1
Declare @@counter int
Declare @@month int
set @@counter=0
Declare @@slno int
Declare @@cRemarks varchar(100)
Declare @@cName varchar(50)
Declare @@Date date

set @@month = 1
Declare tmepTbl cursor
For
Select slno,cName,cRemarks,date from tblDataUpdateTest

Open tmepTbl /* Opening the cursor */

fetch next from tmepTbl
into @@slno,@@cName,@@cRemarks,@@Date

while @@fetch_Status=-1
begin

if not exists (select cRemarks from tblDataUpdateTest where MONTH(Date) = @@month AND YEAR(Date) = 2012)
begin
insert into tblDataUpdateTest (cName, cRemarks,[Date]) values (@@cName,'s',(DateAdd(yy, 2012-1900,DateAdd(m,  @@month - 1, 01 - 1))))
end

fetch next from tmepTbl
into @@slno,@@cName,@@cRemarks,@@Date

set @@month=@@month+1
end
close tmepTbl
Deallocate tmepTbl

今私のテーブル

cName cRemarks Date
name1 Text1    2012-01-01
name2 Text2    2012-01-01

私は次のことをしたい:

cName cRemarks Date
name1 Text1    2012-01-01
name1 Text1    2012-02-01
name1 Text1    2012-03-01
name2 Text2    2012-01-01
name2 Text2    2012-02-01
name2 Text2    2012-03-01

等々。

ありがとう!

4

1 に答える 1

0

カーソルの代わりに再帰 CTE を使用する方がよいでしょうか? 次に例を示します。

DECLARE @y INT
DECLARE @m INT
DECLARE @n INT
SET @y = 2012
SET @m = 1
SET @n = 3

;WITH dates(d, m) AS(
    SELECT CONVERT(DATE, CONVERT(VARCHAR(4), @y) + '-01-01'), 1
    UNION ALL
    SELECT CONVERT(DATE, CONVERT(VARCHAR(4), @y) + '-' + CASE WHEN m + 1 < 10 THEN '0' ELSE '' END + CONVERT(VARCHAR(2), m + 1) + '-01')
        , m + 1 
    FROM dates
    WHERE m < @n
)
INSERT INTO tblDataUpdateTest(cName, cRemarks,[Date])
    SELECT cName, cRemarks, [date] FROM (
    SELECT cName, cRemarks, dates.d AS [date]
    FROM tblDataUpdateTest
    CROSS JOIN dates) t
    WHERE NOT(EXISTS(SELECT * FROM tblDataUpdateTest WHERE cName = t.cName AND [date] = t.[date]))
OPTION(MAXRECURSION 11)

SELECT * FROM tblDataUpdateTest ORDER BY cName
于 2012-05-27T22:41:07.917 に答える