【问题标题】:SQL Server 2008 R2 update while loop with temporary tablesSQL Server 2008 R2 使用临时表更新 while 循环
【发布时间】:2014-07-08 08:36:43
【问题描述】:

我在更新表格(比如 TableA)时遇到了困难。 目前我正在使用 2 个循环。

1st Loop is based on the data from temp table named : ##tempTableB
2nd Loop is based on the data from temp table named : ##tempTableC.

如何使用这样的脚本示例更新 TableA。

declare @amount money;
declare @i int =1;
declare @total int;

declare @j int = 1;
declare @total2 int;

declare @numberid nvarchar(14);
declare @num int;
declare @principal money;
declare @margin money;
declare @insurance money;

select @numberid=numberid,@amount=amount from ##temptableB
set @total = @rowcount; -- 48 rows result

while @i <= @total
begin

    select @num=num,
    @principal=principal,
    @margin=margin,
    @insurance=insurance from ##tempTableC

    set @total2 = @rowcount;-- 48 rows result

    while @j <=total2
    begin

    update tableA set
    payedprincipal=@principal,payed_margin=@margin,payed_insurance=@insurance` 
    where numberid=@numberid
    set @j=@j+1
    end

set @i=@i+1
end

【问题讨论】:

  • 您知道@numberid 只是来自##temptableB 的一条随机记录吗?您是否知道您可以在一个不带循环的单个 UPDATE 语句中根据其他表中的多条记录在一个表中 UPDATE 多条记录?

标签: sql-server temp-tables


【解决方案1】:

只需编写一个可以根据表 A 中的值更新表 B 或 C 的直接更新脚本。这是一个可以在新查询窗口中运行的示例,它仅根据所涉及的表之间的 JOIN 更新值:

设置温度表

declare @tempA table (id int, val int)
declare @tempB table (id int, val int)

-- Source table
insert into @tempA (id, val) values (1,100)
insert into @tempA (id, val) values (2,200)
insert into @tempA (id, val) values (3,300)
insert into @tempA (id, val) values (4,400)

-- table that requires updates
insert into @tempB (id, val) values (1,0)
insert into @tempB (id, val) values (2,0)
insert into @tempB (id, val) values (3,0)
insert into @tempB (id, val) values (4,0)

-- output initial values 
Select * from @tempA
Select * from @tempB

然后运行更新脚本以使用来自@tempA 的值更新@tempBval 列,其中id 列匹配:

Update b 
SET val = a.val
FROM @tempB b 
     INNER JOIN @tempA a on a.id = b.id

-- output the updated values
Select * from @tempA
Select * from @tempB

【讨论】:

  • 感谢您的提示和快速回复。虽然这并不完美。实际上,这是我的批量付款处理器的一个简单版本,分期付款。在这种情况下,trans 记录将在##tempTableB 上,Inst Schedule 在##tempTableB 上。需要一个一个处理trans记录,因为在##temptableB上会有分期付款的div部分。付款按保险、保证金和本金的比例依次处理和分离。分割后的超额款项将存储到下一行。我认为基于集合不合适。
  • 我接受这个作为替代解决方案。无论如何,谢谢。