这就是我正在做的事情:
while (@counter < 3 and @newBalance >0)
begin
CASE
when @counter = 1 then ( @monFee1 = @monthlyFee, @newBalance = @newBalance-@fee)
when @counter = 2 then ( @monFee2 = @monthlyFee, @newBalance = @newBalance-@fee)
END
@counter = @counter +1
end
我收到此错误:
关键字'CASE'附近的语法不正确。
不知道为什么。请帮忙!
答案 0 :(得分:7)
对于你提出的建议,你应该使用IF语句
While (@counter < 3 and @newBalance >0)
Begin
If @Counter = 1 Then
Begin
Set @monFee1 = @monthlyFee
Set @newBalance = @newBalance-@fee
End
If @Counter = 2 Then
Begin
Set @monFee2 = @monthlyFee
Set @newBalance = @newBalance-@fee
End
Set @counter = @counter +1
End
答案 1 :(得分:6)
不,SQL中的CASE结构是返回一个值,而不是程序流。您需要将其分解为IF语句。
答案 2 :(得分:3)
CASE语句不像处理程序代码中的表兄一样用于分支逻辑。它将在结果集中返回结果,以便在为变量赋值时,可以确定该值不是您要分配给哪个变量的值。
不幸的是,
(@monFee1 = @counter, @newBalance = @newBalance-@fee)
不会返回值。
使用If / Else bracnching逻辑的另一种方法是
while (@counter < 3 and @newBalance >0)
begin
IF @counter = 1
THEN
SET @monFee1 = @monthlyFee
SET @newBalance = @newBalance-@fee
END
ELSE IF @counter = 2
BEGIN
SET @monFee2 = @monthlyFee
SET @newBalance = @newBalance-@fee
END
SET @counter = @counter +1
end
答案 3 :(得分:0)
你不应该在这里使用while循环。您实际上只检查@newBalance的值一次。考虑:
@monFee1 = @monthlyFee
@newBalance = @newBalance-@fee
IF @newBalance > 0
BEGIN
@monFee2 = @monthlyFee
@newBalance = @newBalance-@fee
END
答案 4 :(得分:0)
由于CASE是一个表达式,您可以在SET赋值语句中使用它。
WHILE (@counter < 3 and @newBalance >0)
BEGIN
SET @monFee1 = CASE WHEN @Counter=1
THEN @monthlyFee ELSE @monFee1 END
SET @monFee2 = CASE WHEN @Counter=2
THEN @monthlyFee ELSE @monFee2 END
SET @newBalance = @newBalance - CASE WHEN @Counter in (1, 2)
THEN @fee ELSE 0 END
SET @counter = @counter +1
END
它也可以在SELECT赋值语句中。
WHILE (@counter < 3 and @newBalance >0)
BEGIN
SELECT
@monFee1 = CASE WHEN @Counter=1
THEN @monthlyFee ELSE @monFee1 END,
@monFee2 = CASE WHEN @Counter=2
THEN @monthlyFee ELSE @monFee2 END,
@newBalance = @newBalance - CASE WHEN @Counter in (1, 2)
THEN @fee ELSE 0 END,
@counter = @counter +1
END
PS:祝你的老龄化报告好运......