我可以在 WHILE 循环中使用 CASE 语句吗?
这就是我正在做的:
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”附近的语法不正确。
不知道为什么。请帮忙!
This is what I'm doing:
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
I get this error:
Incorrect syntax near the keyword 'CASE'.
No idea why. Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,SQL中的CASE结构是为了返回一个值,而不是为了程序流程。您需要将其分解为 IF 语句。
No, the CASE structure in SQL is to return a value, not for program flow. You need to break it into IF statements.
对于您所提议的内容,您应该使用 IF 语句
For what you are proposing, you should use IF statements
CASE 语句不像过程代码中的同类语句那样用于分支逻辑。它将返回结果集中的结果,以便当您将值分配给变量时,您可以确定该值是什么而不是分配给哪个变量。
不幸的是,
不返回值。
使用 If/Else 分支逻辑的替代方法是
The CASE statement isn't used for branching logic in the same way as its cousin in procedural code. It will return a result in a result set so that when your assigning a value to a variable, you can determine what the value will be not which variable you are assigning to.
Unfortunately,
doesn't return a value.
An alternate approach using If/Else bracnching logic would be
你不应该在这里使用 while 循环。您实际上只检查了一次 @newBalance 的值。考虑:
You shouldn't use a while loop here. You are effectively only checking the value of @newBalance one time. Consider:
由于 CASE 是一个表达式,因此您可以在 SET 赋值语句中使用它。
它也可以在 SELECT 赋值语句中。
PS:祝你的衰老报告好运......
Since CASE is an expression, you can use it within a SET assignment statement.
It can also within a SELECT assignment statement.
PS: good luck with your aging report...