当 TVP 数据第一行没有内容时出现“无效的 SQL 数据类型”错误

问题描述 投票:0回答:1

当我尝试在具有 TVP 的 SQL Server 数据库中通过 pyodbc 启动存储过程且列具有 None 值时,出现此错误。

[HY004] [Microsoft][SQL Server 的 ODBC 驱动程序 18]无效的 SQL 数据类型 (0) (SQLBindParameter)

有什么方法可以向 pyodbc 指示列的数据类型还是我必须在 TVP 中放弃?

这就是我正在尝试的:

cursor.execute("{CALL dbo.stored_procedure (?, ?)}", (None, tvp_data))

第一个变量我不关心,第二个变量是我的 TVP。只要 TVP 本身的列中没有 None ,一切都会正常工作,但如果有,我会收到错误。

python sql-server pyodbc
1个回答
0
投票

这是参数元数据发现的已知限制,如 GitHub herehere 上所述。解决方法包括:

选项 1. 对 TVP 数据进行排序,以便第一行不包含

None
值。

选项 2. 在匿名代码块中使用

OPENJSON()
并将 TVP 数据作为 JSON 字符串传递。

tvp_data = [(1, None), (2, "Bravo")]
tvp_json = [dict(zip(["id", "txt"], row)) for row in tvp_data]

sql = """\
SET NOCOUNT ON;
DECLARE @tvp dbo.issue_1229_table_type;
INSERT INTO @tvp (id, txt)
SELECT id, txt FROM OPENJSON(?)
WITH (
    id int '$.id',
    txt nvarchar(50) '$.txt'
);
EXEC issue_1229_sp @tvp
"""
results = crsr.execute(sql, json.dumps(tvp_json, default=str)).fetchall()
print(results)
# [(1, None), (2, 'Bravo')]

(示例复制自我自己的 GitHub 评论此处。)

© www.soinside.com 2019 - 2024. All rights reserved.