表A
id     name
1     办公设备
10    生产设备
11    娱乐设备
表B
id     name    pid
1     计算机    1
2      卡车     10
3     打印机  1
4      台球   11
4      篮球     11a.id和b.pid是关联的
需要查询出来的结果
id     name         pid
1     办公设备      1,3
10    生产设备       2
11    娱乐设备      4,5

解决方案 »

  1.   

    --> 测试数据:#a
    if object_id('tempdb.dbo.#a') is not null drop table #a
    create table #a(id int, name varchar(8))
    insert into #a
    select 1, '办公设备' union all
    select 10, '生产设备' union all
    select 11, '娱乐设备'
    --> 测试数据:#b
    if object_id('tempdb.dbo.#b') is not null drop table #b
    create table #b(id int, name varchar(8), pid int)
    insert into #b
    select 1, '计算机', 1 union all
    select 2, '卡车', 10 union all
    select 3, '打印机', 1 union all
    select 4, '台球', 11 union all
    select 4, '篮球', 11select id, name, pid=stuff((select ','+ltrim(id) from #b where pid=t.id for xml path('')),1,1,'') from #a t/*
    a.id和b.pid是关联的
    需要查询出来的结果
    id name pid
    1 办公设备 1,3
    10 生产设备 2
    11 娱乐设备 4,5
    */
      

  2.   

    select *
    ,replace((select id  as 'data()' from b where a.id=pid for xml path('')),' ',',') AS PID
    from a
      

  3.   

    select *
    ,replace((select id  as 'data()' from b where a.id=pid for xml path('')),' ',',') AS PID
    from aid          name     PID
    ----------- -------- ------------
    1           办公设备     1,3
    10          生产设备     2
    11          娱乐设备     4,4(3 行受影响)
      

  4.   

    谢谢两位兄台,我刚从下面帖里找到方法和2楼的一样,谁知道你们已经帮我解决了。
    http://topic.csdn.net/u/20090924/11/9a920a29-a6a2-428f-9fab-577058304898.html