How would you handle a SELECT
statement in SQL Server 2012 when there is a possibility that a column value might be NULL
?
I am attempting to conditionally insert a record via JDBC if the record does not exist, and return the ID associated with the record if it does exist. For simplicity, I have opted to use a SELECT
query, followed by an INSERT
query for this.
My SELECT
query looks like this, except (a, b, c, d, e) correspond to meaningful names (use your imagination).
SELECT id
FROM dim_repository
WHERE a = ?
AND b = ?
AND c = ?
AND d = ?
AND e = ?
However, if (a)
is NULL
then the query will return an empty resultset since (a) = NULL
isn't a valid query (i.e. since a different verb is used for NULLs
and scalar values).
Would the only way to fix the query be to add a conditional selection as follows?
SELECT id
FROM dim_repository
WHERE (a = ? OR a IS ?)
AND (b = ? OR b IS ?)
AND (c = ? OR c IS ?)
AND (d = ? OR d IS ?)
AND (e = ? OR e IS ?)
This approach is valid, although since the table that I am working with has 16 different columns, I'm hesitant to use 30 conditional statements in my SELECT
call.