简体   繁体   中英

cursor in sqlsrv_query not working

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.

update table2
    set cola = t1.col1
from table2 t2
join table1 t1 on t1.col2 = t2.colb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM