读书人

请问UPDATE两个表之间关联更新。

发布时间: 2012-09-10 11:02:32 作者: rapoo

请教UPDATE,两个表之间关联更新。!急!!!!!
表A结构:
列a 列b 列c

表B结构:
列a 列m 列n

希望用update,用表A与表B的a列进行关联,把表B的m列用b列填充,n列用c列填充。该如何实现。谢谢!
表A中a列的值都是唯一的。表B中a/m/n三列都存在重复。谢谢!

[解决办法]

SQL code
update 表Aset 列b=(select top 1 m列 from 表B where a列=t.a列),    列c=(select top 1 c列 from 表B where a列=t.a列)from 表A t
[解决办法]
SQL code
--> 测试数据: @Adeclare @A table (a int,b varchar(1),c varchar(1))insert into @Aselect 1,null,null union allselect 2,null,null union allselect 3,null,null union allselect 4,null,null--> 测试数据: @Bdeclare @B table (a int,m varchar(1),n varchar(1))insert into @Bselect 1,'a','j' union allselect 1,'b','k' union allselect 2,'c','l' union allselect 2,'d','m' union allselect 3,'e','n' union allselect 3,'f','o' union allselect 3,'g','p' union allselect 4,'h','q' union allselect 4,'i','r'--更新前select * from @A/*a           b    c----------- ---- ----1           NULL NULL2           NULL NULL3           NULL NULL4           NULL NULL*/--更新后update @Aset b=(select top 1 m from @B where a=t.a),    c=(select top 1 n from @B where a=t.a)from @A tselect * from @A/*a           b    c----------- ---- ----1           a    j2           c    l3           e    n4           h    q*/ 

读书人网 >SQL Server

热点推荐