日期:2014-05-18  浏览次数:20478 次

SQL 更新语句
表1:
ID1 ID2 ID3 ID4  
11 1 1 334  
11 2 1 324 
12 3 4 355
13 5 4 764
……  

表2
ID1 ID2 ID3 ID4  
11 1 1 NULL 
11 2 1 NULL 
12 3 4 NULL 
13 5 4 NULL 
……
各位高手,怎么把表2的ID4列更新为同表1的一样
后边还有很多数据,但是规律就是这样的……

------解决方案--------------------
SQL code
update t2
set t2.id4=t1.id4
from t1
where t1.id1=t2.id1 and t1.id2=t2.id2 and t1.id3=t.id3

------解决方案--------------------
SQL code
--> 测试数据: #tab1
if object_id('tempdb.dbo.#tab1') is not null drop table #tab1
create table #tab1 ([ID1] int,[ID2] int,[ID3] int,[ID4] int)
insert into #tab1
select 11,1,1,334 union all
select 11,2,1,324 union all
select 12,3,4,355 union all
select 13,5,4,764

if object_id('tempdb.dbo.#tab2') is not null drop table #tab2
create table #tab2 ([ID1] int,[ID2] int,[ID3] int,[ID4] sql_variant)
insert into #tab2
select 11,1,1,null union all
select 11,2,1,null union all
select 12,3,4,null union all
select 13,5,4,null

--更新
update #tab2 set ID4=t1.ID4 from #tab1 t1,#tab2 t2 
where t1.ID1=t2.ID1 and t1.ID2=t2.ID2 and t1.ID3=t2.ID3