我的一个变量在 while 循环中没有正确更新时遇到问题。我正在使用Microsoft SQL Server Management Studio 2012。
use database
declare @sumPrice decimal(10,2) = 0.0
declare @rowPrice decimal(10,2) = 0.0
declare @numRows int = (select count(*) from Products)
declare @iterator int = 1
while @iterator <= @numRows
begin
set @rowPrice = (select UnitPrice from Products p
where p.ProductID = @iterator and UnitsInStock > 110)
set @sumPrice += @rowPrice
set @iterator += 1
end
Print 'The sum is ' + convert(varchar, @sumPrice, 1)
go
问题是@sumPrice永远不会更新。 @iterator更新得很好,到最后,它的 77。在调试代码时,@rowPrice会更新为当前行的价格,但是当需要将其添加到@sumPrice时,它永远不会发生。@sumPrice在整个循环中保持空白,打印语句甚至也不会打印。我该如何解决这个问题?
编辑:找到了该问题的解决方案,事实证明,将 NULL 添加到变量中会导致变量返回 NULL。您需要使用合并函数,而不是直接添加到变量中。
@sumprice
以NULL
值开头。 向NULL
值添加任何内容都会返回NULL
。
这很容易解决。 在循环之前初始化值:
set @sumprice = 0;
在循环之前。
或者,将增量调整为:
set @sumPrice = coalesce(@sumPrice, 0) + @rowPrice;
为了安全起见,您应该确保@rowPrice
也不是NULL
:
set @sumPrice = coalesce(@sumPrice, 0) + coalesce(@rowPrice, 0);
如果@rowPrice
NULL
一次迭代,那么您将丢失该值。
它不起作用的原因是,当库存单位不大于 110 时,内部查询返回 p.ProductID 的空值。 NULL 与实际值相加,结果为 NULL。 解决方法是合并空值。您还需要设置已修复的变量值。
while @iterator <= @numRows
begin
set @rowPrice = (SELECT COALESCE((select UnitPrice
from Products p
where p.ProductID = @iterator and UnitsInStock > 110
), 0)
)
set @sumPrice += @rowPrice
set @iterator += 1
end
SELECT 'The sum is ' + CAST(@sumPrice as varchar)