1. 程式人生 > >sqlserver中用不重複的條件更新兩個表對應欄位欄位。

sqlserver中用不重複的條件更新兩個表對應欄位欄位。

表T1和表T2,表T2的F23欄位用表T1的F3欄位更新,條件是T1.F2=T2.F22並且只有T1.F2和T2.F22是一一對應,T1只有一條記錄和T2對應,例子如下:

create table t1(f1 int,f2 varchar(10),f3 varchar(10));

create table t2(f21 int,f22 varchar(10),f23 varchar(10));


insert into t1 values(1,'111','abc');
insert into t1 values(2,'111','abc');
insert into t1 values(3,'222','ddd');


insert into t2 values(1,'111',null);
insert into t2 values(2,'222',null);


update t2 set t2.f23 = t1.f3
from t1,t2
where t1.f2=t2.f22 and exists(select t3.f2,COUNT(*) from t1 as t3 where t3.f2=t1.f2 group by t3.f2 having COUNT(*) =1 );


select * from t1;
select * from t2;