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

将A表某字段值随机插入B表某字段
A表有100条记录,B表有1000条记录,A.c1字段和B.c2字段均有值。
我要将A表100条记录的A.c1字段值随机插入B表1000条记录的B.c2字段,求SQL语句或存储过程!

------解决方案--------------------
SQL code

declare @A table (c1 int,c2 varchar(1))
insert into @A
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d'

declare @B table (c1 int,c2 varchar(1))
insert into @B
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e' union all
select 6,'f' union all
select 7,'g' union all
select 8,'h' union all
select 9,'i' union all
select 10,'j'

declare @i int set @i=0
update @B set c2=(select top 1 c1 from @A order by newid()),@i=@i+1
select * from @B
/*
c1          c2
----------- ----
1           4
2           2
3           3
4           1
5           4
6           2
7           4
8           2
9           1
10          2
*/