循环在SQL存储过程中不起作用

时间:2013-02-08 15:22:28

标签: sql-server tsql stored-procedures

我有一个包含多个问卷的数据库,每个问卷都有相关的(多选)问题,每个问题都有相关答案。

我正在尝试创建一个存储过程,该过程将仅使用调查问卷的ID删除所有问题和相关答案。 我的存储过程如下所示:

ALTER PROCEDURE [dbo].[DeleteQuestionnnaire] 

    @EnqueteID bigint
AS

BEGIN
    SET NOCOUNT ON

    DECLARE @QID bigint

    DECLARE questionCursor CURSOR FOR
        SELECT ID FROM questions WHERE EnqueteID = @EnqueteID

    OPEN questionCursor;

    FETCH questionCursor INTO @QID  

    WHILE(@@fetch_status=0)
    BEGIN

    -- this is not working correct, the related answers are NOT being deleted

        FETCH questionCursor INTO @QID
        DELETE FROM answers WHERE QuestionID=@QID

    END

    CLOSE questionCursor

        --  this works fine, the questions are being deleted
    DELETE FROM questions WHERE EnqueteID=@EnqueteID

END

相关的问题正在被删除,但相关的答案没有,所以我在循环中做错了,是否有人看到它是什么?

提前致谢

3 个答案:

答案 0 :(得分:2)

你的光标有点奇怪,因为FETCH NEXT通常是循环中的最后一个语句(参见documentation中的示例),所以实际上你获取的第一个值会立即替换为第二个。在游标中添加一些PRINT语句以检查@QID的当前值将显示此信息。

但真正的答案是根本不使用光标,这里没有必要:

delete from dbo.answers where questionid in (
    select questionid from dbo.questions where EnqueteID = @EnqueteID
)
delete from dbo.questions where EnqueteID = @EnqueteID

答案 1 :(得分:1)

整体光标看起来不错。我将fetch语句(在循环内)移动到结尾之前的右下角。目前,您正在将第一个值提取到参数中,然后在您进入循环后立即获取第二个值;从不使用它时有效地抛出第一个值。

WHILE(@@fetch_status=0)
BEGIN

    --SELECT @QID and Answers to see if you're getting the right values
    SELECT @QID
    SELECT * FROM Answers WHERE QuestionID = @QID
    -- DELETE FROM answers WHERE QuestionID=@QID

    --Fetch should be right before the loop ends
    FETCH questionCursor INTO @QID   
END

答案 2 :(得分:1)

你是在第一个,然后是第二个,所以第一个没有被删除

FETCH questionCursor INTO @QID  

WHILE(@@fetch_status=0)
BEGIN

    DELETE FROM answers WHERE QuestionID=@QID
    FETCH questionCursor INTO @QID

END

delete answers 
where QuestionID in (select SELECT ID FROM questions WHERE EnqueteID = @EnqueteID);
go
delete questions WHERE EnqueteID = @EnqueteID;