Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Updating multiple values from 1 table to another

Author  Topic 

Umar001
Starting Member

10 Posts

Posted - 2012-05-09 : 01:41:40
How can I update multiple values in 1 table based on the values from another table, do i need to use cursor ? or any loop ?
every time there may be different values in temptable or sometime there may be no values at all. in this particular example there are three columns for which I need to update the values in temptable2
from temptable1 i.e Name, Phone and Address

I know when updating we need to give field names and field values however in this case this will be coming from another table at runtime.

Can I use any loop to execute
 Update dbo.temptable set ColumnValue = val1 
where ColumnName = val2


For you to see what I have please use following code


drop table #temptable
Create Table #temptable
( id int not null primary key,
val1 varchar(50),
val2 varchar(50))


insert into #temptable(id,val1,val2)
values
(1,'Name','John'),
(2,'Phone','1111111'),
(3,'Address','Newton Australia')
select * from #temptable


drop table #temptable2
Create Table #temptable2
( columnname varchar(50),
columnvalue varchar(50))

insert into #temptable2(columnname)
values
('Address'),
('idnumber'),
('Phone'),
('OfficeNumber'),
('Surname')
select * from #temptable2


Umar Memon

vijays3
Constraint Violating Yak Guru

354 Posts

Posted - 2012-05-09 : 07:23:29
try this



update t2 set t2.columnvalue= t1.val2

from #temptable2 t2 inner join #temptable t1 on t1.val1 =t2.columnname
Go to Top of Page
   

- Advertisement -