我正在尝试在 Python 脚本中使用 OPENJSON 将一些基本的 JSON 导入到 SQL 数据库中。我最初尝试使用更复杂的 JSON 文件,但为了这篇文章对其进行了简化。这是我拥有的:
sql_statement = "declare @json nvarchar(max) = '{\"name\":\"James\"}'; SELECT * FROM OPENJSON(@json) WITH (name nvarchar(20))"
cursor.execute(sql_statement)
cursor.commit()
connection.close()
我收到的错误:
pypyodbc.ProgrammingError: (u'42000', u"[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.")
关于为什么我会看到这个错误有什么想法吗?我成功地能够使用相同的 pypyodbc/数据库配置执行其他 SQL 查询。
最佳答案
问题可能是您的数据库运行在较旧的兼容级别,其中 OPEN JSON 不可用。
要查找数据库的兼容级别,请运行以下 SQL 语句:
SELECT compatibility_level FROM sys.databases WHERE name = 'your_db_name';
如果结果为 120 或更低,您需要将兼容级别更新为 130,方法是运行:
ALTER DATABASE your_db_name SET COMPATIBILITY_LEVEL = 130;
注意:如果您的数据库实际上是 Azure SQL DB,您还应该检查版本,因为 OPEN JSON 不适用于 12.x 之前的版本
关于python - pypyodbc:关键字 "WITH"附近的 OPENJSON 语法不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555706/