Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
select col1
from table1
case when @col2 is null then left outer join else join end
table2 on (join condition)


Above is my query, i want to choose between left outer or right outer join based on 1 condition.

I want to know a better solution for implementing the above problem
Posted
Updated 5-Mar-13 21:43pm
v2

Hi,

Use Dynamic Query.... Search in Google

how to write a dynamic query in sql[^]
 
Share this answer
 
SQL
DECLARE @col2 INT,@join VARCHAR(100),@query NVARCHAR(1000)
SELECT @join=CASE WHEN @col2 IS NULL THEN 'left outer join' ELSE 'join'END
SELECT @query='select *
from [table1] '+@join +
 ' [table2] c on [Join condition]'
 EXEC SP_EXECUTESQL @query
 
Share this answer
 
Two ways
1. (example)
SQL
declare @col2 int
set @col2 = NULL ; -- value is null it will give result for LEFT OUTER JOIN only
--change value null to something else it will give result for JOIN only

with a as
(select 1 as a
union all
select 2 as a)


select *
from a
left outer join
(select 1 as a, 'a' as b) as b on a.a=b.a
where
a.a =( case when @col2 is null then a.a else b.a end)

so,as per solution 1 set your query like this
SQL
select col1
from table1
left outer join
table2 on table1.col1 =table2.col1
where table1.col1 = (case when @col2 is null then table1.col1 else table2.col1 end)


2.
SQL
if (@col2 is null)
    begin
        select col1
        from table1
        left outer join 
        table2 on table1.col1=table2.col1
    end
else
    begin
        select col1
        from table1
        join 
        table2 on table1.col1=table2.col1
    End


Happy Coding!
:)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900