嵌套游标,代码不会更新游标之外的表

时间:2012-11-01 21:48:33

标签: sql cursor

我正在研究这个嵌套游标。 major_cursor中的更新语句不更新表。我知道所有的循环都在工作,因为print语句会打印出期望值,但是在edu_suffix_stage_test中没有任何更新。我希望有人提出建议!

对于每个id,都有一个专业的数据行,以及获得学位的年份。我需要将它们串在一起。

例如,REID 10013有两个度数的两个记录:

'38的土木工程, 和'土木工程'在41年。

我需要建立edusuffix,因此它等于“土木工程”38,“41年土木工程”。 在edu_suffix_stage_test中,我最终需要每个reid一个edusuffix。

感谢。

这是我的代码:

DECLARE @reid_outside nvarchar(20), @major nvarchar(50), @classof nvarchar(5),
 @edusuffix_inside varchar(80), @note nvarchar(50), @reid_inside nvarchar(20),
@edusuffix_outside varchar(80)


DECLARE education_cursor CURSOR FOR 
SELECT  reid, edusuffix
FROM edu_suffix_stage_test
where reid < 1005
--ORDER BY reid

OPEN education_cursor

FETCH NEXT FROM education_cursor 
INTO @reid_outside, @edusuffix_outside

WHILE @@FETCH_STATUS = 0
BEGIN

    SELECT @note = 'building edusuffix for ' 
    PRINT @note
    PRINT @reid_outside

    -- Declare an inner cursor based   
    -- on reid from the outer cursor.

    DECLARE major_cursor CURSOR FOR 
    SELECT v.reid, 
    v.EduMajor, v.EduClassOF
    FROM  re_education v
   WHERE v.REID = @reid_outside  -- Variable value from the outer cursor 
--order by v.REID 
FOR UPDATE of edusuffix


    OPEN major_cursor
    FETCH NEXT FROM major_cursor INTO @reid_inside, @major, @classof

    WHILE @@FETCH_STATUS = 0
    BEGIN

        SELECT @edusuffix_inside = @major +' '+ @classof +', '
        PRINT @edusuffix_inside

    update edu_suffix_stage_test
    set edusuffix = case when @edusuffix_outside = null then ''+ @edusuffix_inside 
            else @edusuffix_outside + ', '+@edusuffix_inside end
    from edu_suffix_stage_test a
where  -- a.reid = @reid_inside
current of education_cursor
Print ' updated edusuffix'

        FETCH NEXT FROM major_cursor INTO @reid_inside, @major, @classof
        END

    CLOSE major_cursor
    DEALLOCATE major_cursor

    FETCH NEXT FROM education_cursor 
    INTO @reid_outside, @edusuffix_outside
END 
CLOSE education_cursor
DEALLOCATE education_cursor

1 个答案:

答案 0 :(得分:0)

实际上游标没有任何问题。 我的更新声明有问题! 我不知道我在想什么,比较null这种方式是行不通的。我正在研究一个更好的case语句,并将使用isnull()。我完成后会发布。