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

多个CD连接查询名字
有这样两个表

一个是  
CDS  
1,2,3  
1,3  

另一个是
CD Name
1 孙
2 李
3 王

怎么把第一个表的名字表示出来
CDS Name  
1,2,3 孙,李,王  
1,3 孙,王  




------解决方案--------------------
SQL code
if not object_id('t1') is null
    drop table t1
Go
Create table t1([CDS] nvarchar(5))
Insert t1
select N'1,2,3' union all
select N'1,3'
Go
if not object_id('t2') is null
    drop table t2
Go
Create table t2([CD] int,[Name] nvarchar(1))
Insert t2
select 1,N'孙' union all
select 2,N'李' union all
select 3,N'王'
Go
select [CDS],
        stuff((select ','+[Name]
        from t2 
        where charindex(','+ltrim([CD] )+',',','+t.[CDS] +',')>0
        for xml path('')),1,1,'')Name
from t1 t