读书人

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

发布时间: 2012-05-11 12:55:37 作者: rapoo

多个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 

读书人网 >SQL Server

热点推荐