2013-02-07 193 views
1

我試圖在select語句中像這樣在SQL Server 2005中使用case語句,並且出現錯誤「只有一個表達式可以在子查詢沒有與EXISTS一起引入時在選擇列表中指定。 「不能在SQL查詢中使用一個Case?!SQL查詢中的Case語句

declare @TypeofDayID int 
set @TypeofDayID = (Select TypeofDayID from RepInfo where RepInfoID = @RepInfoID) 


Select CASE 
    WHEN @TypeofDayID = 1 
     THEN (Select * from RepInfo RD inner join SellingInfo S on S.RepInfoID = @RepInfoID) 
    WHEN @TypeofDayID = 2 
     THEN (Select * from RepInfo RD inner join UpgradingInfo U on U.RepInfoID = @RepDailyID) 
    WHEN @TypeofDayID = 9 or @TypeofDayID = 10 
     THEN (Select * from RepInfo RD inner join DeliveryInfo D on D.RepDailyID = @RepDailyID) 
    END 
from RepInfo RD 
+0

當你使用你的'SELECT'一個'CASE'語句來定義單個列,你不能這樣做'SELECT CASE WHEN東西然後選擇* ...' – Lamak

+0

號子查詢可以」噸。使用if塊。 – Kermit

+0

與上述同意。您可以在SELECT中使用CASE來測試值,但如果您正在尋找執行不同類型的代碼,那麼您將需要使用IF來代替。 – Matt

回答

4

CASE不用於邏輯流控...使用IF/ELSE IF代替:

declare @TypeofDayID int 
set @TypeofDayID = (Select TypeofDayID from RepInfo where RepInfoID = @RepInfoID) 

IF @TypeofDayID = 1 
    Select * 
    from RepInfo RD inner join SellingInfo S on S.RepInfoID = @RepInfoID 
ELSE IF @TypeofDayID = 2 
    Select * 
    from RepInfo RD inner join UpgradingInfo U on U.RepInfoID = @RepDailyID 
ELSE IF @TypeofDayID = 9 or @TypeofDayID = 10 
    Select * 
    from RepInfo RD inner join DeliveryInfo D on D.RepDailyID = @RepDailyID 

記住......由於您使用SELECT *,並且加入到不同的基於@TypeOfDayID的表格,您最終可能會得到鋸齒狀的結果集,這意味着您將根據採用哪個分支來獲得不同數量的列。

這可以通過編程工作痛苦,所以這將是避免SELECT *因爲這個原因,還有其他原因個好主意......

+0

不僅是SELECT *,而且它還運行着這些條件下性能較差的機會。 – StingyJack

0

我認爲你正在試圖做能做的事這樣更好地處理。

declare @TypeofDayID int 
set @TypeofDayID = (Select TypeofDayID from RepInfo where RepInfoID = @RepInfoID) 

IF @TypeofDayID = 1 
    Select * 
    from RepInfo RD 
    inner join SellingInfo S on S.RepInfoID = @RepInfoID 
ELSE IF @TypeofDayID = 2 
    Select * 
    from RepInfo RD 
    inner join UpgradingInfo U on U.RepInfoID = @RepDailyID 
ELSE IF @TypeofDayID = 9 or @TypeofDayID = 10 
    Select * 
    from RepInfo RD 
    inner join DeliveryInfo D on D.RepDailyID = @RepDailyID