2

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)
0

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Am I correct that the first one will not work with sql-server?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.