简体   繁体   中英

How to parameterize SQL query when the parameter can sometimes be NULL?

With pyodbc I can parametrize the query like this;

value = "testval"

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

cursor.execute(query, value)

But the problem is that if the value is None, the query should look like this;

value = None

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

cursor.execute(query)

So how should the query look like when the value can either be None or a string;

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

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

cursor.execute(query, value)

The solution is to use the ISO/ANSI standard NULL -safe comparison:

WHERE Column IS NOT DISTINCT FROM ?

Not all databases support this, so you can also use:

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

If you are reluctant to pass the parameter twice, you can include it in the FROM clause:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM