2013-03-11 19 views
2

我有一個存儲過程,我想根據傳入的參數查詢生產或「工作進行中」表格。我可以編寫兩個單獨的存儲過程,但我認爲這值得一試。根據參數查詢不同的表格

東西沿着線:

create procedure getUserDetails 
    @userID int, 
    @prod varchar(5) 
as 
    begin 
     select * from 
      if (@prod = 'true') 
      Begin 
       userprod_table 
      else 
       userwip_table 
      end 
    where something = 'something' 
END 

這是在所有可能的?我不想寫2 SP是幾乎相同: -/

+0

不是真的有關,但[在生產代碼中使用SELECT *](http://stackoverflow.com/a/3180435/1048425)是** **從來沒有一個好主意。你的兩張桌子是否有相同的列? – GarethD 2013-03-11 14:55:27

回答

1

爲什麼不使用一個簡單的if(@prod = 'true')聲明如下圖所示:

if (@prod = 'true') 
begin 
    select * from userprod_table where something = 'something' 
end else 
begin 
    select * from userwip_table where something = 'something' 
end 
0

你可以使用一個CTE讓你的主查詢不重複

with usertable as 
(
    select * from userprod_table where 1 = @flag 
    union 
    select * from userwip_table where 0 = @flag 
) 
select ... from usertable ... 
相關問題