[英]Pyodbc, how to get results from SQL Server stored procedure
I have a stored procedure I have to work with.我有一个必须使用的存储过程。 From SQL developer is gives results that look like a table.
SQL 开发人员提供的结果看起来像一个表格。 But when I try to get the results with Pyodbc, I only get:
但是当我尝试使用 Pyodbc 获得结果时,我只能得到:
Error: No results.
错误:没有结果。 Previous SQL was not a query.
以前的 SQL 不是查询。
I think it's how the results are being produced maybe, because it's using select.我认为这可能是结果的产生方式,因为它使用了选择。 I'm not sure how to get the output.
我不确定如何获得输出。 I've tried a few other ideas from guides and SO questions, but I've had no luck.
我从指南和 SO 问题中尝试了其他一些想法,但我没有运气。
The SP looks like this: SP 看起来像这样:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE schema.spname
AS
BEGIN
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRY
DECLARE @NewLogID BIGINT
DECLARE @recs INT = 0
DECLARE @Process VARCHAR(200) = OBJECT_NAME(@@PROCID)
-- Log the Process
EXEC anrm.WriteANRMLog @ProcessName = @Process,@ReturnLogID=@NewLogID OUTPUT
SELECT receipt_id, order_id, user_id
FROM tableA
WHERE A.Qty>0
AND datesent IS NULL
--EXEC schema.othertable @RecordCount = @recs,@logid= @NewLogID, @ReturnLogID=@NewLogID OUTPUT
PRINT @Process + ' - Completed'
END TRY
BEGIN CATCH
EXEC anrm.PrintError
--EXEC anrm.LogNRMError
END CATCH
END
And I'm trying to get the results, most recently, like this.最近,我正在尝试像这样获得结果。
try:
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' +
server+';DATABASE='+database+';UID='+username+';PWD=' + password)
cnxn.autocommit = True
cursor = cnxn.cursor()
cursor.execute("SET NOCOUNT ON; exec schema.spname")
row = cursor.fetchone()
while row:
print(str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
cursor.close()
del cursor
cnxn.close()
except Exception as e:
print("Error: %s" % e)
Can you modify the SP?可以修改SP吗? If so, instead of running the select in the SP, have it insert results into a temp table.
如果是这样,不要在 SP 中运行选择,而是让它将结果插入到临时表中。 Then in python
然后在python中
cursor.execute("exec schema.spname")
cursor.execute("select * from #my_temp_table")
cursor.execute("drop table #my_temp_table")
Does this work for you?这对你有用吗?
# SQL Server format
cursor.execute("exec sp_dosomething(123, 'abc')")
# ODBC format
cursor.execute("{call sp_dosomething(123, 'abc')}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.