I'm having difficulties in updating a table (say TableA). Currently I'm using 2 loops.
1st Loop is based on the data from temp table named : ##tempTableB
2nd Loop is based on the data from temp table named : ##tempTableC.
How do update TableA with a script sample like this.
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
Just write a direct update script that can update table B or C based on values from table A. Here's a sample you can run in a new query window that simply updates values based on a JOIN
between the tables that are involved:
SETUP TEMP TABLES
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
Then run an update script to update the val
column of @tempB
with the values from @tempA
where the id
columns match:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.