Given this SQL statement that uses a cursor to loop through each row of a table and update a row in another table:
DECLARE @x varchar(100)
DECLARE @y varchar(100)
DECLARE c CURSOR FOR
SELECT col1, col2 FROM table
OPEN c
FETCH NEXT FROM c INTO @x, @y
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE table2 SET cola = @x WHERE colb = @y
FETCH NEXT FROM c INTO @x, @y
END
CLOSE c
DEALLOCATE c;
If I run this statement directly within SQL console or Navicat, everything works as expected. But if I run it in PHP using:
sqlsrv_query($sql)
only SOME of the rows in table2 are actually updated. It seems the cursor in the SQL statement does not properly execute, perhaps sqlsrv_query returns while the statement’s cursor is still running?
Is there a way to instruct sqlsrv_query to ‘wait’ until the statement is fully done executing before returning a result?
How about something like this instead of a cursor. The only reason I’ve ever had to write a cursor was to convert an older model into a newer model, in order to run some business rules and such for the conversion. I do not have any cursors running in production.