有表 
table1id          name          id21              a            x1              a            y1              a            z table2id          name          id21              a          null现在想让table2的id2变为table2id          name          id21              a          x,y,z该怎么操作

解决方案 »

  1.   

    SELECT   id,name,scort=STUFF((SELECT ','+id2 FROM #table1  FOR XML PATH('') ),1,1,'' ) 
    FROM #table1 a
    group by id,name
      

  2.   

    上面的语句应该跟你的要求相似.你稍微调整一下.用了 For XML.
      

  3.   

    恩,赞成husang608的说法,简单说你就是想做一个字符串的累加用某个分隔符隔开,for xml path满足这么干
      

  4.   

    我想把table2的id2 update成x,y,z的格式 请问用for xml path可以实现吗
      

  5.   

    -->测试数据
    if object_id('tb1')is not null
    drop table tb1
    go
    create table tb1(id int,name varchar(4),id2  varchar(4))
    insert into tb1
    select '1','a','x' union all
    select '1','a','y' union all
    select '1','a','z' if object_id('tb2')is not null
    drop table tb2
    go
    create table tb2(id int,name varchar(4),id2  varchar(4))
    insert into tb2
    select '1','a',null--     select * from tb1
    --     select * from tb2
    -->测试查询
    select id,name,id2=stuff((select ','+id2 from tb1 for xml path('') ),1,1,'' )  
    from tb2 a
    group by id,name
    -->测试结果/*
    ---- -------- ------------
    id name id2
    1 a x,y,z
    */
      

  6.   

    --注意表2的id2列字段长度
    update tb2 set id2=stuff((select ','+id2 from tb1 for xml path('') ),1,1,'' )