2012-05-27 25 views
2

我遇到隨機結束的cursur問題。我想爲每個元素生成一行,因此對於每個元素,2012年的每個月都會有一行。如果某個特定月份缺少一行,它也應該創建該行。現在遊標永不在T-SQL中結束

,它產生於每月的最後一個元素的行,直到一年2057

現在,我對每個元素的行,直到每月,直到一年2057只爲我的表中的一個元素。

我的表設計:

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 @@[email protected]@month+1 
end 
close tmepTbl 
Deallocate tmepTbl 

我現在表

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

我想follwing發生:

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 

等。

謝謝!

回答

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 
+0

Thx!我會將光標轉換爲此 – Knaks