当前位置: 代码迷 >> Sql Server >> 多个CD连接查询名字解决方案
  详细解决方案

多个CD连接查询名字解决方案

热度:25   发布时间:2016-04-27 12:55:58.0
多个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 t1GoCreate table t1([CDS] nvarchar(5))Insert t1select N'1,2,3' union allselect N'1,3'Goif not object_id('t2') is null    drop table t2GoCreate table t2([CD] int,[Name] nvarchar(1))Insert t2select 1,N'孙' union allselect 2,N'李' union allselect 3,N'王'Goselect [CDS],        stuff((select ','+[Name]        from t2         where charindex(','+ltrim([CD] )+',',','+t.[CDS] +',')>0        for xml path('')),1,1,'')Namefrom t1 t
  相关解决方案