0

I am not sure what is wrong here, please help.

I am trying to loop over set of result and to use id's from set to execute another select query.

DECLARE @MyCursor CURSOR;
DECLARE @ID int;
DECLARE @Name varchar(200)
BEGIN
    SET @MyCursor = CURSOR FOR
    SELECT  ID, Name FROM UserGroups

OPEN @MyCursor 
  FETCH @MyCursor INTO @ID, @Name;

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT * FROM ErrorToNotify INNER JOIN ErrorMessages ON
    ErrorToNotify.ErrMsgID = ErrorMessages.ID
    INNER JOIN InterfaceErrors ON
    InterfaceErrors.ErrMessageID = ErrorMessages.ID
     WHERE UserGroupID = @ID 
  FETCH NEXT FROM @MyCursor         
END; 

CLOSE @MyCursor ;
DEALLOCATE @MyCursor;
END;
1
  • Please post the error message you are getting when running your query. Commented Oct 6, 2015 at 10:05

2 Answers 2

3

Use FETCH NEXT FROM @MyCursor INTO @ID, @Name before the loop and at the end of the loop

Edit

My answer solves your syntax errors, but the correct approach is not to use a cursor. Check Rahul's answer.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Will accept your answer in few minutes.
1

You certainly don't need a cursor here rather just need to do another extra join with UserGroups table like below. Moreover, why you are fetching Name column in cursor since you are not using it anywhere.

SELECT * FROM ErrorToNotify 
INNER JOIN ErrorMessages ON ErrorToNotify.ErrMsgID = ErrorMessages.ID
INNER JOIN InterfaceErrors ON InterfaceErrors.ErrMessageID = ErrorMessages.ID
INNER JOIN UserGroups ON ErrorToNotify.UserGroupID  = UserGroups.ID;

1 Comment

Yes, correct. But I need to loop over groups because I have different select for each group, this was just example. Tnx for help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.