I'm creating a query (to eventually be used in a stored procedure) with multiple variations on what criteria is entered in a form. Sometimes there can be an entry, sometimes not. Sometimes the data field has a value, sometimes it's NULL.
The fields in my form are NAME, SSN, and DRLICENSE.
DECLARE @name VARCHAR(30);
DECLARE @ssn VARCHAR(10);
DECLARE @drlic VARCHAR(10);
--(if for example, someone enters data in two of the fields like this...)
SET @name = 'SMITH'
SET @drlic = 'D'
(In stored procedure)
SET @name = @name + '%'
SET @ssn = @ssn + '%'
SET @drlic = @drlic + '%'
SELECT
NAME,
SSN,
DRLICENSE
FROM
TABLE
WHERE
NAME LIKE CASE WHEN LEN(@name) > 1 THEN @name ELSE NAME END
AND SSN LIKE CASE WHEN len(@ssn) > 1 THEN @ssn ELSE SSN END
AND DRLICENSE LIKE CASE WHEN LEN(@drlic) > 1 THEN @drlic ELSE DRLICENSE END
The idea behind my case statement is to check the variable for usage and perform a like if the name
, ssn
, or drlicense
are partial entries.
My question is: how do I account for the case of NULL in the table column (i.e. SSN LIKE SSN
does not work when SSN
is NULL
because SSN IS NULL
needs to be there).