update
您可以在子句中使用效率相当低的嵌套查询结构来做到这一点。
在 SQL Server 语法中:
update tableC
set Name = (select top 1 b.name
from TableB b
where b.name not in (select name from TableA a where a.id = TableC.id)
order by NEWID()
)
TableA的最内层select
从同一个 id 获取所有名称。该where
子句选择不在此列表中的名称。order by () limit 1
随机选择其中一个名称。
根据我对问题的理解,这是一个有效的代码示例:
declare @tableA table (id int, name varchar(2));
declare @tableB table (name varchar(2));
declare @tableC table (id int, name varchar(2))
insert into @tableA(id, name)
select 01, 'A4' union all
select 01, 'SH' union all
select 01, '9K' union all
select 02, 'M1' union all
select 02, 'L4' union all
select 03, '2G' union all
select 03, '99';
insert into @tableB(name)
select '5G' union all
select 'U8' union all
select '02' union all
select '45' union all
select '23' union all
select 'J7' union all
select '99' union all
select '9F' union all
select 'A4' union all
select 'H2';
insert into @tableC(id)
select 01 union all
select 01 union all
select 01 union all
select 02 union all
select 02 union all
select 03 union all
select 03;
/*
select * from @tableA;
select * from @tableB;
select * from @tableC;
*/
update c
set Name = (select top 1 b.name
from @TableB b
where b.name not in (select name from @TableA a where a.id = c.id)
order by NEWID()
)
from @tableC c
select *
from @tableC