首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL用分隔符分割的VALUE 如何从另一张表取得text

2013-07-01 
SQL用分隔符分割的VALUE 怎么从另一张表取得text表AIDVALUES1a,b,c2c,d表BIDtext value1一a2二b3五c4六d想

SQL用分隔符分割的VALUE 怎么从另一张表取得text
表A
ID  VALUES
1   a,b,c
2   c,d

表B
ID  text value
1    一   a
2    二   b
3    五   c
4    六   d

想写SQL 得
字段A  字段B
a,b,c  一,二,五
c,d    五,六

请问怎么写


[解决办法]


with tb(ID,[VALUES])as(
select 1,'a,b,c' union
select 2,'c,d')
,tc(ID,text,value)as(
select 1,'一','a' union
select 2,'二','b' union
select 3,'五','c' union
select 4,'六','d')
,td as(
select [values],tb.ID,text from tb,master..spt_values,tc
where type='p' and SUBSTRING(','+[values],number,1)=',' 
and SUBSTRING([values],number,1)=tc.value
)
select distinct [values],
text=stuff((select ','+text from td where a.ID=ID for xml path('')),1,1,'') from td a

[解决办法]
with A (ID,[VALUES]) as
(
select 1,'a,b,c' union all
select 2,'c,d'
)
,B (ID,[text],[value]) as 
(
select 1,'一','a' union all
select 2,'二','b' union all
select 3,'五','c' union all
select 4,'六','d'
)
,c as
(
select b.*,a.[values]
from b cross join a 
where charindex(b.[value],a.[values])>0
)
SELECTd.[values],[text]=stuff
(
(select ','+RTRIM([text]) as [text()]
from c e where d.[values]=e.[values]
for xml path('')
),1,1,'') FROM c d group by d.[values]

热点排行