我正在尝试将python列表传递给SQL Server查询。我遇到了pyobdc错误。
我尝试了以下方法:
# order_by is a list with 80 strings e.g. ['a','b','c', ...]
placeholders = ", ".join(["?"] * len(order_by))
query = """
SELECT *
FROM my_table_name
ORDER BY (""" + placeholders + ")"
cursor.execute(query, order_by)
这给了我一个pyodbc错误:
','附近的语法不正确。 (102)
我不知道我在哪里语法错误
答案 0 :(得分:1)
查询参数仅用于传递列值,而不用于传递列名称。在需要动态包含对象名称的情况下,您需要使用动态SQL(字符串替换),例如:
schema_name = 'dbo'
table_name = 'Donor'
sql = """\
SELECT QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA=? AND TABLE_NAME=?
ORDER BY ORDINAL_POSITION
"""
crsr.execute(sql, schema_name, table_name)
columns = ', '.join([x[0] for x in crsr.fetchall()])
sql = f"SELECT * FROM [{schema_name}].[{table_name}] ORDER BY {columns}"
print(sql)
# SELECT * FROM [dbo].[Donor] ORDER BY [id], [last_name], [first_name]