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

关于表值更新问题
比如现在有a,b两个表,我想用b表的一个列的值去更新a表的一个列,因为b表的值可能有多个,我取第一个,SQL怎么写?

------解决方案--------------------
比如现在有a,b两个表,我想用b表的一个列的值去更新a表的一个列,因为b表的值可能有多个,我取第一个,SQL怎么写?

update a
set col = c.col
from a,
(select id , min(col) col from b group by id) c
where a.id = c.id



update a
set col = c.col
from a,
(select id , max(col) col from b group by id) c
where a.id = c.id

------解决方案--------------------
update a表
set 列=(select top1 列 from b表 where 关联键=a.关联键)

------解决方案--------------------
update a set ColNam=(select top 1 ColNam1 from b) where 条件
--测试
declare @ta table(Nam varchar(20))
insert @ta select 'aa '
union all select 'bb '

declare @tb table(Nam varchar(20))
insert @tb select 'dd '
union all select 'ee '

update @ta set Nam=(select top 1 Nam from @tb)
select * from @ta