我必须使用表变量参数调用 MS SQLServer 存储过程。
/* Declare a variable that references the type. */
DECLARE @TableVariable AS [AList];
/* Add data to the table variable. */
INSERT INTO @TableVariable (val) VALUES ('value-1');
INSERT INTO @TableVariable (val) VALUES ('value-2');
EXEC [dbo].[sp_MyProc]
@param = @TableVariable
在 SQL Sv Management Studio 中运行良好。我使用 PyOdbc 在 python 中尝试了以下操作:
cursor.execute("declare @TableVariable AS [AList]")
for a in mylist:
cursor.execute("INSERT INTO @TableVariable (val) VALUES (?)", a)
cursor.execute("{call dbo.sp_MyProc(@TableVariable)}")
出现以下错误:错误 42000:必须声明表变量。变量在不同的执行步骤中不存在。 我也试过:
sql = "DECLARE @TableVariable AS [AList]; "
for a in mylist:
sql = sql + "INSERT INTO @TableVariable (val) VALUES ('{}'); ".format(a)
sql = sql + "EXEC [dbo].[sp_MyProc] @param = @TableVariable"
cursor.execute(sql)
出现以下错误:无结果。以前的 SQL 不是查询。 没有机会了
sql = sql + "{call dbo.sp_MyProc(@TableVariable)}"
有人知道如何使用 Pyodbc 处理这个问题吗?
最佳答案
现在问题的根源是 SQL Server variable具有定义它的 batch 的范围。每次调用 cursor.execute 都是一个单独的批处理,即使它们在同一个事务中。
有几种方法可以解决这个问题。最直接的方法是重写您的 Python 代码,以便将所有内容作为一个批处理发送。 (我在我的测试服务器上对此进行了测试,只要您添加 set nocount on 或使用 nextset 跳过中间结果,它就应该可以工作。)
一种更间接的方法是重写过程以查找临时表而不是表变量,然后只创建和填充临时表而不是表变量。 temp table不是在存储过程中创建的具有创建它的 session 的范围。
关于python - pyodbc,使用表变量调用存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13377877/