小编典典

当参数有时可以为NULL时,如何参数化SQL查询?

sql

通过pyodbc我可以参数化这样的查询;

value = "testval"

query = \
    """
    SELECT *
    FROM TestTable
    WHERE Column = ?;
    """

cursor.execute(query, value)

但是问题在于,如果avalue为None,则查询应如下所示;

value = None

query = \
    """
    SELECT *
    FROM TestTable
    WHERE Column IS NULL;
    """

cursor.execute(query)

因此,当查询value可以为None或字符串时,查询应如何?

value = get_value()  # can return a string or None

query = \
    """
    SELECT *
    FROM TestTable
    WHERE Column ???????????
    """

cursor.execute(query, value)

阅读 170

收藏
2021-04-28

共1个答案

小编典典

解决方案是使用ISO / ANSI标准-安全NULL比较:

WHERE Column IS NOT DISTINCT FROM ?

并非所有数据库都支持此功能,因此您还可以使用:

WHERE Column = ? OR (Column IS NULL AND ? IS NULL)

如果您不愿意两次传递参数,则可以在FROM子句中包含它:

. . .
FROM . . . CROSS JOIN
     (SELECT ? as compColumn) params
WHERE (Column = params.compColumn0 or (Column IS NULL and params.compColumn IS NULL)
2021-04-28