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

求一存储过程或sql语句,批量动态更新
求一个存储过程或sql语句,可以根据table1表中的uid,到table2中查出相应的dtype,更新到table1中的dtype中

table1中有字段uid,dtype
其中uid是有值的
uid有重复数据,非空
dtype在这个表中是空的,目的就是往这里边加入值
uid dtype
110  
120
120
130..

table2中有字段uid,dtype
uid为唯一
dtype有重复数据,非空
uid dtype

110 a
120 a
130 b
140 c
150 c

存储过程执行或sql语句后,table1中的数据为
uid dtype
110 a
120 a
120 a
130 b
..

------解决方案--------------------
SQL code

update tbl1 set type=a.type from tbl2 a where a.uid=tbl1.uid

------解决方案--------------------
SQL code

create table #t1(id int, xtype char(1))
insert into #t1 select 1,NULL
union all select 2,NULL
union all select 2,NULL
union all select 3,NULL
union all select 4,NULL


create table #t2(id int, xtype char(1))
insert into #t2 select 1,'a'
union all select 2,'b'
union all select 3,'c'
union all select 4,'d'

update #t1 set xtype=(select xtype from #t2 where #t1.id=#t2.id)

select * from #t1

-----------------------------------

id          xtype
----------- -----
1           a
2           b
2           b
3           c
4           d

(5 行受影响)