0

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

我正在尝试创建一个存储过程,该过程将删除所有问题和相关答案,仅包含调查问卷的 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

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

提前致谢

4

3 回答 3

2

您的光标有点奇怪,因为FETCH NEXT它通常是循环中的最后一条语句(请参阅文档中的示例),因此实际上您获取的第一个值会立即被第二个替换。将一些PRINT语句添加到游标中以检查 的当前值@QID将显示这一点。

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

delete from dbo.answers where questionid in (
    select questionid from dbo.questions where EnqueteID = @EnqueteID
)
delete from dbo.questions where EnqueteID = @EnqueteID
于 2013-02-08T15:57:01.397 回答
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
于 2013-02-08T15:42:18.490 回答
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;
于 2013-02-08T15:58:08.587 回答