简体   繁体   中英

How to get the value returned by a stored procedure called from python in SQL server 2008 R2

I need to check the returned value from a stored procedure on SQL server 2008 R2.

 import pyodbc
 sql_str  = """
                DECLARE @return_value int 
                SET @return_value  = -1 
                INSERT INTO [my_database].[dbo].[my_table] 
                EXEC @return_value = [my_database].[dbo].[my_stored_procedure] 
                if @return_value <> 0  
                BEGIN 
                    EXEC sys.sp_addmessage 60000, 16, ' test sp returns wrong code !  ' 
                        RAISERROR (60000, 16, 1) 
                END  
               """
sql_str_connect_db = " DRIVER={SQL server};SERVER={my_server};DATABASE={my_db};UID=my_id;PWD=my_password "
cnxn = pyodbc.connect(sql_str_connect_db )
cursor_test = cnxn.cursor()
cursor_test.execute(sql_str)
cnxn_test.commit()

But, I got error:

pyodbc.Error: ('HY007', '[HY007] [Microsoft][ODBC SQL Server Driver]Associated statement is not prepared (0) (SQLNumResultCols)')

And, how to check the value of "@return_value" in python ?

After searching , I cannot find a solution.

Thanks

You should be able to just select it like this in your SQL:

SELECT @return_value AS return_value

Then use your cursor to fetch the records:

rows = cursor_test.fetchall()
    for row in rows:
        print(row.return_value)

Regards,

-Tim

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