SQL Server 2008 R2使用临时表更新while循环

时间:2014-07-08 08:36:44

标签: sql-server temp-tables

我在更新表时遇到困难(例如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

1 个答案:

答案 0 :(得分:0)

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

设置TEMP表格

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

然后运行更新脚本,使用val列匹配的@tempB值更新@tempA 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