I am trying to get some data from a table and possibly filtering it depending on the result from another query.
The code is something like this:
DECLARE @TestTable TABLE(TestID INT)
INSERT INTO @TestTable
SELECT TestID from v_Lookuptable Where SomeID = @input
SELECT DISTINCT
C.[Level],
C.Name
FROM
dbo.CPackage CP
Right outer join @TestTable TT on TT.TestID = CP.TestID
WHERE
AND (TT.TestID is null OR Exists( Select TT.TestID from @TestTable
inner join dbo.CProduct CP on CP.TestID = MT.TestID
where TT.TestID = CP.TestID
))
My problem is that if I pass in my currently scenario the @input as 1, then the top part returns some numbers: 1, 2, 3
But if I pass @input as 2, then the top part returns nothing because nothing matches.
The idea is that if nothing matches, return everything in the bottom query, so from dbo.CPackage, else, only return those things where the TestID match.
I have tried various things like changing the joins, case statements, using ISNULL and collasce. Also I have tried to remove the part TT.TestID is null and it then works if the top table returns something, but when I add it again it returns everything and never filters. So I know the logic is wrong… I just can’t figure out the correct logic for this…. :S
Is it possible? I presume it is…
Cheers
Robin
** Solution **
Remove the join and just put it in the where filter…
SELECT DISTINCT
C.[Level],
C.Name
FROM
dbo.CPackage CP
WHERE
CP.TestID = coalesce( (select distinct TestID from v_Lookuptable LT
where LT.SomeID = @input), CP.TestID )
Does this give you what you’re looking for:
Or, you may even be able to rewrite the entire query like this: