I am creating a cursor using select statement that would return 4 values (18, 13, 14 and 15). I am trying to iterate through the cursor and display the value for now. I am expecting 4 print statements, but I see lot more than that.
Here is the code:
PRINT '***** *****'
GO
DECLARE curs CURSOR FOR
SELECT ID FROM CUSTOMER WHERE SSN LIKE '%1803'
GO
DECLARE @ID int
OPEN curs
FETCH NEXT curs INTO @ID
WHILE @@sqlstatus = 0
BEGIN
PRINT '* current value: %1! ', @ID
FETCH NEXT curs INTO @ID
END
CLOSE curs
DEALLOCATE CURSOR curs
GO
Here is the output:
***** *****
* current value: 18
* current value: 18
* current value: 13
* current value: 18
* current value: 13
* current value: 14
* current value: 18
* current value: 13
* current value: 14
* current value: 15
* current value: 18
* current value: 13
* current value: 14
* current value: 15
It seems like a simple iterate over cursor and I cannot understand why I am seeing so many print statements, I want to only see 18, 13, 14 and 15. I am using Sybase ASE 15.5 and Razor SQL client. Can someone help me with this?
* Edit * I didn't see the issue when I used Sybase Central (for ASE). The results were inconsistent when I used other IDEs.
Firstly make sure you always use an order by with any SQL nowadays to ensure you get data back in the order you expect. You don't know how the database will optimise the query at the backend so be specific.
Also check a direct select and check how many rows match for 'SSN LIKE '%1803' to begin with to cross-check the rowcounts against the cursor.