You can do this with a rather inefficient, nested query structure in an update
clause.
In SQL Server syntax:
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()
)
The inner most select
from TableA gets all the names from the same id. The where
clause chooses names that are not in this list. The order by () limit 1
randomly selects one of the names.
Here is an example of the code that works, according to my understanding of the problem:
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…