2016-02-04 31 views
0

如何使用類似if或case的東西......如何將以下代碼合併爲一個?以動態方式結合了兩個T-SQL

if @para = 'test' 
begin 
select * from Table A where status='A' and id in (select id from Table B) 
end 
else if @para = 'others' 
begin 
select * from Table A where status='A' and id in (select id from Table c) 
end 

像SELECT * FROM表A其中id在如果@para = XXX然後(從表B中選擇的id)

感謝。

+0

你能否詳細說明多一點,你在找依據的情況下,查詢? –

+0

是的!我想將兩個SQL合併成一個。我可以這樣做嗎? @ArunprasanthKV – chloe06060

+0

實際上這是一個子查詢... ...像select * from table where col1 = xxx and col2 = xxx and id in(................).. so if我使用的情況下,..恐怖味精會提示子查詢不能做到這一點 – chloe06060

回答

1

試試這個:

select * 
from Table A 
where (id in (select id from Table B) and @para = 'test') 
     OR 
     (id in (select id from Table c) and @para = 'others') 
+0

非常感謝〜它真的有用 – chloe06060

1

當您標記存儲過程中我做到了作爲一個...嘗試像這樣

create procedure GetData (@para nvarchar(100)) 
as 
begin 

declare @sql nvarchar(max) 

set @sql = case 
      when @para = 'test' 
     then 
      'Select * from TableA A 
       join TableB B on A.id = B.ID' 
     else -- if @para = 'others' goes into else 
      'Select * from TableA A 
       join TableB B on A.id = B.ID' 
     end 

execute (@sql) 
end