如何为逗号分隔的代码字符串获取相应的逗号分隔文本?

时间:2011-04-12 07:38:39

标签: sql-server-2005 tsql

我有一个表,有一个名为“locations”的列,其类型为varchar(max)。它带有逗号分隔的代码串,例如'1, 3, 4'。另一方面,我有一张表将这些代码映射到某些位置,例如

1 -- British
2 -- New Zealand
3 -- Hong Kong
4 -- Taiwan

我的问题是,我正在制作一个VIEW,它会将列“location”的内容映射并替换为相应的逗号分隔文本,例如: '1, 3, 4'将为'British, Hong Kong, Taiwan'

这对公司项目来说非常紧迫,请提出建议。

谢谢!

此致 威廉

1 个答案:

答案 0 :(得分:3)

可能有更简单的解决方案,但这是一种方式。

表格结构

create table Locations(LocationID int, Location varchar(50))
create table OtherTable(ID int, Locations varchar(max))

测试数据

insert into Locations values(1, 'Location <1>')
insert into Locations values(2, 'Location <2>')
insert into Locations values(3, 'Location <3>')
insert into Locations values(4, 'Location <4>')
insert into Locations values(5, 'Location <5>')

insert into OtherTable values (1, '')
insert into OtherTable values (2, '2')
insert into OtherTable values (3, '1, 3 ,5')

查询

;with cte as
(
  select 
    T.ID,
    coalesce(L.Location, '') as Location
  from OtherTable as T
    cross apply
      (select cast('<r>'+replace(T.Locations, ',', '</r><r>')+'</r>' as xml)) LocXML(XMLCol)
    cross apply
      LocXML.XMLCol.nodes('r') LocID(IDCol) 
    left outer join Locations as L
      on L.LocationID = LocID.IDCol.value('.', 'int')
)
select
  C1.ID,
  stuff((select ', '+C2.Location
         from cte as C2 
         where C1.ID = C2.ID
         for xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 2, '') as Locations
from cte as C1
group by C1.ID

结果

ID  Locations
--- ----------------------------------------
1   
2   Location <2>
3   Location <1>, Location <3>, Location <5>