Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

sql server - Python - pyodbc call stored procedure with parameter name

I need to call a SqlServer stored procedure from python2.7 via pyodbc module with input parameter name.

I tried based on documentation by input parameter order:

cursor.execute('{CALL [SP_NAME](?,?)}',
              ('value', 'value'))

It works, but I need to pass parameter name of stored procedure because order of stored procedure input parameter always changes. So I need to pass them by name.

cursor.execute('{CALL [SP_NAME](@param1name,@param2name)}',
              ('value', 'value'))

However this doesn't work. What's the correct syntax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tested this using the following stored procedure in SQL Server 2008 R2:

CREATE PROCEDURE [dbo].[breakfast] 
    @person varchar(50) = 'nobody', 
    @food varchar(50) = 'tofu'
AS
BEGIN
    SET NOCOUNT ON;
    SELECT @person + ' likes to eat ' + @food
END

The Bad News ("CALL")

I found that

sql = """
{ CALL breakfast (@food=?, @person=?) }
"""
params = ('bacon','Gord')
crsr.execute(sql, params)

gave inconsistent results.

With the {SQL Server Native Client 10.0} ODBC driver it ignored the parameter names and treated the parameters as positional, yielding ...

bacon likes to eat Gord

... and with the older {SQL Server} ODBC driver I just got the error

DataError: ('22018', '[22018] [Microsoft][ODBC SQL Server Driver]Invalid character value for cast specification (0) (SQLExecDirectW)')

The Good News ("EXEC")

I found that

sql = """
EXEC breakfast @food=?, @person=?
"""
params = ('bacon','Gord')
crsr.execute(sql, params)

gave me the following (correct) result using both ODBC drivers

Gord likes to eat bacon

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...