Skip to content
Advertisement

Iterate over two loops (CURSOR and WHILE) and print the records grouped by location

I want to print the records grouped by each location (in this case they are 2), duly ordered.

I’m testing with a cursor but it prints the same location twice.

How can I fix this?

Results

Edited with suggestions from users. But we have the same results

Advertisement

Answer

You’re not using the cursor data for anything – therefore you inner query gets all your locations. You need to obtain the value from the cursor and then use it to filter your inner query. The following changes are required:

  1. Add DECLARE @Location AS VARCHAR(50); near the start.
  2. Modify your fetch‘s to be FETCH NEXT FROM ExternCursor INTO @Location;
  3. Modify your inner where to be WHERE [LOCATION] = @Location
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement