简体   繁体   中英

How to loop through tables in python that come from a stored procedure in sql. With While Loop and Pyodbc?

cur = connection.cursor()
cur.execute("set nocount on exec SP") 
while(cur.nextset()):
    print(cur.description)

This code produces 10 tables, sometimes 11. I want to be able to use a while loop because the amount of tables might differ each time. The issue with this code above is it produces 9 tables instead of 10 because cur.nextset() runs and skips the first table.

What can I do to work around this? I want the code the work in a loop. I need a better function that works with the pyodbc module.

Any ideas?

You can avoid skipping the first result set by moving your nextset() check to the bottom of the loop:

cur.execute("set nocount on exec SP")
while True:
    # do stuff with the result set
    if not cur.nextset():
        break
print("All result sets have been processed.")

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