Jan 30, 2016

Updating a temporary table from another table by matching column values.

Hello,

Im new to this Forum and I need to update a temporary table based on matching values from another table.For example i have two tables

table1                                                    

month(varchar)  sales(int)                        

1                              -

2                               -
3                               -
4                               -
5                               -
  table2
month(varchar)      sales(int)
2                              100
4                               50
5                               100
In this example i need to update  the  table1 sales column with table2 sales column by matching the month value of both the tables..


ans is 
UPDATE t1 SET t1.sales=t2.sales
FROM table1 t1 INNER JOIN table2 t2 ON t1.MONTH=t2.MONTH


You can simply try the left outer join:

create table #table1 (month varchar(10), sales int)
insert into #table1 values ('1',null)
insert into #table1 values ('2',null)
insert into #table1 values ('3',null)
insert into #table1 values ('4',null)
insert into #table1 values ('5',null)
create table #table2 (month varchar(10), sales int)
insert into #table2 values ('2',100)
insert into #table2 values ('4',50)
insert into #table2 values ('5',100)
select a.[month], b.sales from #table1 a left outer join #table2 b
on a.[month]=b.[month]
drop table #table1
drop table #table2

If you want to update table1 

Please try the below query
update a set a.[sales]=b.sales from #table1 a 
left outer join #table2 b on a.[month]=b.[month] 
select * from #table1 

No comments:

Post a Comment