I have a database with multiple questionnaires, each questionnaire has related (multiplechoice) questions, and each question has related answers.
I’m trying to create a stored procedure that will delete all questions and related answers with only the ID of the questionnaire.
My stored procedure looks like this:
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
the related questions are being deleted but the related answers not, so I’m doing something wrong in my loop, is there anybody out there who sees what it is?
Thanks in advance
Your cursor is slightly odd, in that
FETCH NEXTis usually the last statement in the loop (see the example from the documentation), so in fact the first value you fetch is immediately replaced by the second one. Adding somePRINTstatements into the cursor to check the current value of@QIDwould show this.But the real answer is not to use a cursor at all, it’s unnecessary here: