2011-06-30 49 views
0

我必須在表之間執行'左'或'內部'連接操作取決於我的存儲過程中的輸入參數。我知道如何做到這一點很簡單:左或內部加入取決於參數

if flag = 0 
begin 
select t1.*, t2.* from t1 
inner join t2 on t2.id=t1.id 
end 
else 
begin 
select t1.*, t2.* from t1 
left join t2 on t2.id=t1.id 
end 

有沒有更多的解決方案?謝謝

回答

3

你只能用做左做這樣的事情

select t1.*, t2.* from t1 
left outer join t2 on t2.id=t1.id 
WHERE flag = 1 OR t2.id IS NOT NULL 
0

加入你沒有提到的語言,所以也許是這樣的:

select t1.*, t2.* from t1 
left join t2 on t2.id=t1.id 

if flag = 0 
begin 
where t2.id is not null 
end 
0
select t1.*, t2.* 
    from t1 
     inner join t2 on t2.id = t1.id 
    where flag = 0 
UNION 
select t1.*, t2.* 
    from t1 
     left outer join t2 on t2.id = t1.id 
    where coalesce(flag, 1) <> 0;