使用 python pyodbc 捕获存储过程输出

Capture stored procedure output with python pyodbc

我有一个存储过程,我正在使用 Python 脚本和 Pyodbc 模块调用它。代码如下所示:

import pyodbc
pyodbc.pooling=False
oConnexion = pyodbc.connect("driver={Teradata};dbcname=myServer;DefaultDatabase=myDB;uid=myUser;pwd=myPassword;charset=utf8;", autocommit=True)
oConnexion.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')
oConnexion.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8')
oConnexion.setencoding(encoding='utf-8')
oCursor = oConnexion.cursor()
oQueryRegisterBatch = "CALL DEV_AUDIT.SP_AUDIT_BATCH('ED_DATA_QUALITY_MANUAL', 'REGISTER', '1900-01-01 00:00:00.000000', '2999-12-31 00:00:00.000000');"
oCursor.execute(oQueryRegisterBatch)
for row in oCursor:
    print (row)

存储过程创建一个新记录和returns记录ID (BATCH_KEY)。当我在 Teradata 中执行存储过程时,它 returns 正确 BATCH_KEY 但我无法在 Python 中捕获它。我收到以下错误消息而不是值:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pyodbc.ProgrammingError: No results.  Previous SQL was not a query.

我可以在调用存储过程后通过查询 table 来检索 BATCH_KEY,但我想避免。能否请您告知如何捕获存储过程的输出?

谢谢

根据 pyodbc 包的文档,无法捕获存储过程的输出。这记录在这里:https://github.com/mkleehammer/pyodbc/wiki/Calling-Stored-Procedures

pyodbc does not currently implement the optional .callproc method.

根据您的数据库引擎,有一个可行的解决方法,即将对存储过程的调用嵌入到查询中。

Because pyodbc does not have .callproc we need to use a workaround for retrieving the values of output parameters and return values. The specific method will depend on what your particular ODBC driver supports, but for Microsoft's ODBC drivers for SQL Server we can use an "anonymous code block" to EXEC the stored procedure and then SELECT the output parameters and/or return values.

详见上文link。