tags:

views:

133

answers:

2

I would like to decide Inner or outer join ( to the same table) depending on the value. How do I do this? Thanks

I have all my select values here Then bunch of joins And on the last join I would like to do

  CASE 
WHEN RTRIM(LTRIM(@AccountType)) = 'OFX' THEN
INNER JOIN Subscriber.Access.SubscriberOFXAccount  ASOA
                ON SSA.Id = ASOA.SubscriberOFXAccountId AND ASOA.Active = 1
ELSE
LEFT JOIN Subscriber.Access.SubscriberOFXAccount  ASOA2
                ON SSA.Id = ASOA2.SubscriberOFXAccountId 
+1  A: 

You just use an if/else condition to make up the SQL Statement completly:

IF RTRIM(LTRIM(@AccountType)) = 'OFX' THEN
 BEGIN
   SELECT Blah FROM Table WHERE Blah2=SomeThings INNER JOIN MyOtherFooBar ON ...
 END
ELSE
 BEGIN
   SELECT Blah FROM Table WHERE Blah2=SomeThings LEFT JOIN MyOtherFooBar ON ...
 END
JonH
This is what I am doing right now but I thought I need to change only last join depending on the value so If I am able to do conditional join it would be a big help.. Thanks
+1  A: 

How about:

Select ..
From ...
    Left Join Subscriber.Access.SubscriberOFXAccount ASOA 
        ON SSA.Id = ASOA.SubscriberOFXAccountId 
Where RTRIM(LTRIM(@AccountType)) <> 'OFX' Or ASOA.IsActive = 1

Note that by check for IsActive = 1 on a left join, it effectively means a row must exist and thus when @AccountType is not OFX, it will effectively use an inner join.

Thomas
How will this code work as Inner join and outer join? right now when I paste your code it's giving me error on <> sign and IsActive = 1.When @AccountType = 'OFX' how will this work as a inner join?
There's a missing closing parenthesis before the <>.
DyingCactus
I added the missing parenthesis. Notice that I'm checking when @AccountType does NOT equal OFX. When IsActive = 1 is your inner join condition.
Thomas
Thanks for your help. I was trying all this but boss wants 2 separate stored procs.. Which is much easy for me.