k80sg
k80sg

Reputation: 2473

SQL Server + Conditional join

Is there a way which I can perform a conditional join something like this:

   CREATE TABLE #Entity 
   (    
    [AutoID] [int],
    [Code] [nvarchar](50) NOT NULL,
   )

    INSERT #Entity
    EXEC Entity_GetEntitiesByUserId @UserID

    DECLARE @Condition bit = 0

    SELECT * FROM [Stuff] s

       IF @Condition = 1 BEGIN

       INNER JOIN 
       (
        SELECT Code as eCode from
        #Entity
       ) e
        ON E.eCode  = s.EntityCode 

       END

       WHERE DeletedBy IS NULL

Thanks.

Upvotes: 1

Views: 628

Answers (2)

Adam Hey
Adam Hey

Reputation: 1691

I know this is a very old question, but I have a different/simpler solution that works well for me.

Only join on TableC if you supply the param @tableCid

        declare @tableCid int = null;
        Select a.Id, b.AId, -- whatever other columns
        from TableA a
        inner join TableB b on b.AId = a.Id 
        left join TableC c on c.Id = b.CId 
    where
        1= case 
            when @tableCid is not null and c.Id = @tableCid then 1 
            when @tableCid is null then 1
        end
        

Upvotes: 0

Florin Ghita
Florin Ghita

Reputation: 17643

This will do logically what you want:

SELECT * 
FROM [Stuff] s
WHERE 
 DeletedBy IS NULL 
 and (@Condition = 0 or s.EntityCode in (select E.code from #Entitye))

Upvotes: 7

Related Questions