1

我试图在 SQL Server 2005 中像这样的 select 语句中使用 case 语句,但我收到错误“当 EXISTS 未引入子查询时,只能在选择列表中指定一个表达式。” 不能在 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
4

2 回答 2

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 *出于这个原因以及其他原因,最好避免...

于 2013-02-07T20:19:33.250 回答
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
于 2013-02-07T20:21:06.260 回答