返回多行的sql循环更新

时间:2014-06-23 16:39:42

标签: sql sql-server

我必须通过将变量中的值减小来更新列值。

有两个条件: 1.行数= 1 2.行数大于1的地方

我已将其设置为执行单行计数,但在查询返回多行时需要帮助。

set @rowsCounted = (select COUNT(QuantityA) from Offers where WID = @wId and ND = @nd)

if(@rowsCounted = 1)
 begin
  set @QuantityAvailable = (select QuantityA from Offers where WID = @wId and ND = @nd)
  set @QuantityAvailable = (select @QuantityAvailable - @QuantityAdjusted)
  update Offers
   set QuantityA = @QuantityAvailable
   where WID = @wId and ND = @nd
 end
else
 begin
  select @rowsCounted as rowsCounted -- example of 4 rows with values of  = 287,280,288,288
--begin loop as the QuantityA may contain different values

 end

1 个答案:

答案 0 :(得分:0)

如果@QuantityAdjusted对于该过程是常量,那么您只需要一个更新语句。使用基于集合的思想构造而不是基于程序的思想构造:

update Offers
   set QuantityA = QuantityA - @QuantityAdjusted
   where WID = @wId and ND = @nd

这将在基于集合的操作中更新,并且不需要构建自己的循环。这是SQL引擎的一部分。