[英]How to get a SQL Server stored procedure returned rowset using pyodbc?
My question is in close connection to stackoverflow/9915788 . 我的问题与stackoverflow / 9915788密切相关。
I am using pyodbc to upload data to an external SQL database and for this I use a stored procedure of that database. 我正在使用pyodbc将数据上传到外部SQL数据库,为此我使用该数据库的存储过程。 This procedure returns two things:
此过程返回两件事:
I managed to read out the integer value using the approach described in the link above, but I would like to read out the rowset as well because I would like to get further information in case of any errors. 我设法使用上面链接中描述的方法读出整数值,但我也想读出行集,因为我想在出现任何错误时获取更多信息。
Any ideas how to do this? 任何想法如何做到这一点? I'm not a SQL expert, but in my understanding a rowset should be a "cursor like" object since it should be possible to loop that row;
我不是SQL专家,但根据我的理解,行集应该是一个“像游标一样”的对象,因为它应该可以循环该行; but how do I get this in a select statement?
但是如何在select语句中得到它?
This is how I get the integer value: 这是我得到整数值的方法:
def CallStoredProc(conn, procName, *args):
sql = """SET NOCOUNT ON;
DECLARE @ret int
EXEC @ret = %s %s
SELECT @ret""" % (procName, ','.join(['?'] * len(args)))
return conn.execute(sql, args).fetchall()
But I have no idea how to get the row, which should also be available somewhere.. 但我不知道如何获得行,这也应该在某处可用..
For the following stored procedure in SQL Server 对于SQL Server中的以下存储过程
CREATE PROCEDURE [dbo].[IsItGord]
@p1 varchar(50) = 'everybody'
AS
BEGIN
DECLARE @retval int;
SET NOCOUNT ON;
IF @p1 = 'Gord'
BEGIN
SET @retval = 0;
SELECT 'Success' AS response;
END
ELSE
BEGIN
SET @retval = -1;
SELECT 'Fail - ' + @p1 + ' is not Gord.' AS response;
END
RETURN @retval;
END
the following pyodbc code 以下pyodbc代码
cnxn = pyodbc.connect(connStr)
sql = """\
DECLARE @return_value int;
EXEC @return_value = [dbo].[IsItGord] ?;
SELECT 'Return Value' = @return_value;
"""
crsr = cnxn.execute(sql, ("Gord"))
data = crsr.fetchall()
print(data)
crsr.nextset()
data = crsr.fetchall()
print(data)
prints 版画
[('Success', )]
[(0, )]
and if I change the .execute()
to 如果我将
.execute()
更改为
crsr = cnxn.execute(sql, ("Fred"))
it prints 它打印
[('Fail - Fred is not Gord.', )]
[(-1, )]
在SQL Server中执行存储过程之前,始终使用:set nocount ON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.