游标永远不会以T-SQL结尾

时间:2012-05-27 22:05:35

标签: tsql cursor

我有一个随机结束的游标问题。我想为每个元素生成一行,因此对于每个元素,2012年每个月都有一行。如果特定月份缺少一行,它也应该创建该行。

现在,它为每个月的最后一个元素生成一行,直到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 @@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

等等。

谢谢!

1 个答案:

答案 0 :(得分: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
相关问题