I broke this down into the two parts
1 - Everything where column
key2
matches the parameter
2 - Anything (note the change in wording) where column
key2
is NULL and column
key1
does not appear in the results from 1 above
I then converted that into two Common Table Expressions and UNIONed the results:
;with CTE1 AS
(
SELECT 'CTE1' AS SOURCE, *
FROM @tmp WHERE Key2 = @key
)
, CTE2 AS
(
SELECT 'CTE2' AS SOURCE, *
FROM @tmp WHERE Key2 IS NULL
AND Key1 NOT IN (SELECT Key1 FROM CTE1)
)
SELECT * FROM CTE1 UNION SELECT * FROM CTE2
ORDER BY [Data]
I included the
SOURCE
column just for clarity on where the data was actually coming from - you should remove it.
In terms of setting this up as a function my
@key
would be the parameter to that function. Here are some instructions on how to set up a function if you are not familiar with that -
SQL Server Table-Valued Function By Practical Examples[
^]
Finally here is the test data I used, in case I need to come back to this question :-)
declare @tmp table ([Data] varchar(10), Key1 int, Key2 int)
insert into @tmp ([Data], Key1, Key2) values
('A',1, 1), ('B',1, NULL), ('C',1, 2), ('D',2, NULL), ('E',3, 1)
declare @key int
set @key = 3