I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box.
Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.
import pymssql
con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx')
cur = con.cursor()
query = "EXECUTE blah blah blah"
cur.execute(query)
con.commit()
con.close()
You might also look at using SELECT rather than EXECUTE. EXECUTE is (iirc) basically a SELECT that doesn't actually fetch anything (, just makes side-effects happen).
I'm not a python expert but after a brief perusing of the DB-API 2.0 I believe you should use the "callproc" method of the cursor like this:
Then you'll have the result in the returned value (of the out param) in the "an_out_param" variable.
If you make your procedure produce a table, you can use that result as a substitute for out params.
So instead of:
do
I was able to get an output value from a SQL stored procedure using Python. I could not find good help getting the output values in Python. I figured out the Python syntax myself, so I suspect this is worth posting here:
Here's how I did it, the key is to declare output parameter first:
2016 update (callproc support in pymssql 2.x)
pymssql v2.x offers limited support for
callproc
. It supports OUTPUT parameters using thepymssql.output()
parameter syntax. Note, however, that OUTPUT parameters can only be retrieved withcallproc
if the stored procedure does not also return a result set. That issue is discussed on GitHub here.For stored procedures that do not return a result set
Given the T-SQL stored procedure
the Python code
produces the following output
Notice that
callproc
returns the parameter tuple with the OUTPUT parameter value assigned by the stored procedure (foo[1]
in this case).For stored procedures that return a result set
If the stored procedure returns one or more result sets and also returns output parameters, we need to use an anonymous code block to retrieve the output parameter value(s):
Stored Procedure:
Python code:
Result: