Search code examples
pythonsqlpymssql

get return value from store procedure pymssql


i'm setting up my connection and return error value from sql-server with pymssql framework in python

this is my Python code with pymssql framework

with pymssql.connect(self.server,self.userID,self.password,self.database) as conn:
    with conn.cursor() as cursor:
        msg = curosr.callproc("TESTVALUE")
        print (msg["return"])

and i got error from msg, there is no return variable

this is what i can do if im on C# language to get return value:

errCode = (int)Cmd.Parameters["return"].Value;

this is my store procedure

ALTER PROCEDURE dbo.TESTVALUE
AS
BEGIN
    #Some query
    IF 1 == 1 #Some Logic
       Return -631 #The Return Value that i need to get
END

i need to get the Return -631 value with python code with pymssql framework

how i can get that return value ini python? please help.


Solution

  • You can use an anonymous code block to execute the stored procedure and retrieve the return value:

    sql = """\
    SET NOCOUNT ON;
    DECLARE @rv int;
    EXEC @rv = dbo.TESTVALUE;
    SELECT @rv;
    """
    crsr.execute(sql)
    return_value = crsr.fetchone()[0]
    print(return_value)  # -631