[英]How to retrieve multiple rows from a SQL Server stored procedure using Pyodbc in Jupyter Notebook
I have a stored procedure in SQL Server which takes 3 input parameters and can produce multiple rows as output.我在 SQL 服务器中有一个存储过程,它接受 3 个输入参数并且可以生成多行作为 output。 In fact, it is returning 20 rows in my current case.
事实上,在我目前的情况下,它返回了 20 行。 For instance, if I manually execute the stored procedure from SSMS, I get the following code and partial output, respectively:
例如,如果我从 SSMS 手动执行存储过程,我将分别得到以下代码和部分 output:
Code:代码:
DECLARE @return_value int
EXEC @return_value = [Coverage-Source].[ReadCoverageMapping]
@client = N'Capital BlueCross',
@lineOfBusiness = N'Commercial',
@distributionChannel = N'Retail'
SELECT 'Return Value' = @return_value
GO
Output: Output:
ID Attribute Value CoverageName
-----------------------------------------
1 Copay Yes Retail Base
2 Copay No Retail
. . . .
. . . .
Return Value
20
Now, while I try to read the stored procedure from jupyter notebook using pyodbc, I get an error现在,当我尝试使用 pyodbc 从 jupyter notebook 读取存储过程时,出现错误
Procedure or function ReadCoverageMapping has too many arguments specified
程序或 function ReadCoverageMapping 指定了太多 arguments
I want output something like this:我想要 output 是这样的:
ID Attribute Value CoverageName
------------------------------------------
1 Copay Yes Retail Base
2 Copay No Retail
. . . .
. . . .
I tried this code:我试过这段代码:
client = 'Capital BlueCross'
lineOfBusiness = 'Commercial'
distributionChannel = 'Retail'
cnxn = pyodbc.connect(r'Driver={SQL
Server};Server=MyServer;Database=COV_SRCE_TEST;Trusted_Connection=yes;')
sql = """\
DECLARE @out nvarchar(max);
EXEC [cov_srce_test].[coverage-source].ReadCoverageMapping @client = ?, @lineOfBusiness = ?,
@distributionChannel = ?, @param_out = @out OUTPUT;
SELECT @out AS the_output;
"""
values = (client, lineOfBusiness, distributionChannel)
cnxn.execute(sql, values)
rows = cnxn.fetchall()
while rows:
print(rows)
if cnxn.nextset():
rows = cnxn.fetchall()
else:
rows = None
Is there any way to achieve this?有什么办法可以做到这一点? I tried using multiple ways, but couldn't find a solution.
我尝试使用多种方法,但找不到解决方案。
Those batches are different.这些批次是不同的。 Looks like it should be:
看起来应该是:
sql = """\
DECLARE @return_value int
EXEC @return_value = [Coverage-Source].[ReadCoverageMapping]
@client = ?,
@lineOfBusiness = ?,
@distributionChannel = ?
SELECT 'Return Value' = @return_value
"""
which will output two resultsets, one from the stored procedure, and a second one for the Return value
which you can probably omit.这将 output 两个结果集,一个来自存储过程,另一个用于
Return value
,您可能会忽略它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.