问题描述
我创建了一个测试类型作为包含以下列的表格:
I created a test type as a table with the below columns:
CREATE TYPE [dbo].[TestType] AS TABLE
(
[TestField] [varchar](10) NULL,
[TestField2] [int] NULL
)
然后我创建了一个存储过程,将该表类型作为参数.
I then created a stored procedure the takes that table type as a parameter.
CREATE PROCEDURE TestTypeProcedure (@tt TestType READONLY)
AS
SELECT *
FROM @tt;
我的目标是能够传递类似列表的列表作为表类型的参数.这可能吗?
My goal is to be able to pass something like a list of lists as the parameter for the table type. Is that even possible?
myList = [['Hello!', 1], ['Goodbye!', 2]]
....
cursor.execute('{{Call {TestTypeProcedure} ({?})}}', myList)
推荐答案
您收到该错误是因为表值参数是一个可迭代列表(最好是元组)...
You are getting that error because a table-valued parameter is a list of iterables (preferably tuples) ...
my_tvp = [('Hello!', 1), ('Goodbye!', 2)]
print(f"my_tvp contains {len(my_tvp)} row(s)")
# my_tvp contains 2 row(s)
...如果你直接将它传递给 .execute()
那么每一行都被解释为一个参数值:
... and if you pass that directly to .execute()
then each row is interpreted as a parameter value:
sql = "{CALL TestTypeProcedure (?)}"
params = my_tvp
print(f"calling SP with {len(params)} parameter value(s)")
# calling SP with 2 parameter value(s)
crsr.execute(sql, params) # error
因此,您需要将您的 tvp 包裹在一个元组中以使其成为单个参数值
Therefore, you need to wrap your tvp inside a tuple to make it a single parameter value
sql = "{CALL TestTypeProcedure (?)}"
params = (my_tvp, ) # tuple containing a single tvp "object"
print(f"calling SP with {len(params)} parameter value(s)")
# calling SP with 1 parameter value(s)
crsr.execute(sql, params) # no error
这篇关于是否可以将值从 PYODBC 传递给表类型参数到 SQL Server?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!