How do I include/exclude parts of an intersect query based on variable value SQL Server 2019

31 Views Asked by At

I've written several table-value functions (TVFs) that query junction tables to get a list of recordIDs with specific associations to the main record table.

Then, I have a stored procedure query that uses UNION or INTERSECT of (TVFs) in the WHERE clause to return a full list of recordIDs to be processed in the main query.

declare @att1 int = NULL
declare @att2 int = NULL
select recordID
    , title
    , trackingNumber
from record
where recordID in (
   select * from searchAtt1(@att1)
   UNION
   select * from searchAtt2(@att2)
   )

Passing in NULL values works for the UNION portion since the union is a combined set of both (the returned list includes all records with att1 or att2.

What value do I pass that will allow the INTERSECT to return the proper set of records with att1 and att2. Passing in ZERO (0) or NULL for one of the variables returns an empty set because there are no records in the respective junction table with a 0 or a NULL value.

declare @att1 int = NULL
declare @att2 int = NULL
select recordID
    , title
    , trackingNumber
from record
where recordID in (
   select * from searchAtt1(@att1)
   INTERSECT
   select * from searchAtt2(@att2)
   )

Is there a way to by-pass one of the TVF calls if the value is not passed to the SP or the value is 0 or NULL?

NEW EDIT / CLARIFICATION:

If @att1 = NULL, I want to call ONLY searchAtt2(@att2).

1

There are 1 best solutions below

0
ValNik On

Try this

declare @att1 int = NULL
declare @att2 int = NULL
select recordID
    , title
    , trackingNumber
from record
where recordID in (
   select * from searchAtt1(case when @att1 is not null then @att1 else @att2 end)
   INTERSECT
   select * from searchAtt2(case when @att2 is not null then @att2 else @att1 end)
   )