3个表   table_a     a1  a2  a3
        table_b     b1  a2  a3  c2
        table_c     c1  c1从 a 表中随机获取一条行数据的 a2,a3 插入B ,同时 在c表中随机获取一行数据的c2插入 B

解决方案 »

  1.   


    --建表
    if object_id('ta') is not null drop table ta 
    create table ta 
    (
    --[id] int identity(1,1) not null,
    [a1] varchar(20) null,
    [a2] varchar(20) null,
    [a3] varchar(20) null
    )
    goif object_id('tb') is not null drop table tb 
    create table tb 
    (
    --[id] int identity(1,1) not null,
    [b1] varchar(20) null,
    [a2] varchar(20) null,
    [a3] varchar(20) null,
    [c2] varchar(20) null
    )
    go
    if object_id('tc') is not null drop table tc
    create table tc 
    (
    --[id] int identity(1,1) not null,
    [c1] varchar(20) null,
    [c2] varchar(20) null
    )
    go--插入数据
    insert into ta
    select 'ddd','aa','23434' union all 
    select 'fff','a342','2ff' union all  
    select 'fdf','asdsdf','2fff' union all  
    select 'dsf','agggg','2rrr' union all  
    select 'sf','arrrr','2uuu' union all  
    select 'sdf','awwww','2ggg' union all  
    select 'sd','aee','2fdfd' union all  
    select 'df','ag','2dfdf' 
    go
    insert into tc
    select 'ca','c3434' union all 
    select 'c342','cff' union all  
    select 'csdsdf','cfff' union all  
    select 'cgggg','crrr' union all  
    select 'crrrr','cuuu' union all  
    select 'cwwww','cggg' union all  
    select 'cee','cfdfd' union all  
    select 'cg','cdfdf' --随机选一条插入tb
    insert into tb(a2,a3,c2) 
    select top 1 a2,a3,c2 from ta,tc order by  NEWID()--执行3次插入后查询结果
    /*
    b1      a2      a3      c2
    ==============================================
    NULL ag 2dfdf crrr
    NULL aa 23434 cggg
    NULL a342 2ff cff
    */
    在程序中处理不是更好?
      

  2.   

    insert into tb(a2,a3,c2) 
    select top 1 a2,a3,c2 
    from ta,tc order by  NEWID()