我试图在SQL Server 2005中的select语句中使用case语句,并且我得到错误“当子查询未引入EXISTS时,只能在选择列表中指定一个表达式。”不能在SQL查询中使用一个案例?!
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 :(得分: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 *
是个好主意,以及其他原因......
答案 1 :(得分: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