用另一个表值替换分号分隔值

时间:2015-04-11 06:20:52

标签: sql sql-server

我有两个表,BooksAuthors

Books

ID     Title     Authors
1      apple     1;2;3;
2      cancer    1;5;

Authors

ID     Name
1      John
2      Mike
3      Joe
4      Katy
5      Sara

我需要一个结果是

的查询
ID     Title     Authors
1      apple     John;Mike;Joe
2      cancer    John;Sara

2 个答案:

答案 0 :(得分:2)

这个怎么样?但是,您必须确保Books表中的Authors列始终具有有效数据。

SELECT ID,
       Title,
       STUFF(CAST((SELECT ';' + aut.Name 
                     FROM Authors aut 
                    WHERE aut.ID IN 
                       (SELECT CAST(Split.a.value('.','VARCHAR(max)') AS int) As bid  
                          FROM  
                             ( SELECT CAST ('<M>' + REPLACE(LEFT(Authors, DATALENGTH(Authors)-1), ';', '</M><M>') + '</M>' AS XML) AS Data  
                             ) AS A CROSS APPLY Data.nodes ('/M') AS    Split(a))  
                      FOR XML PATH(''), TYPE))AS nvarchar(max)), 1,1,'')
 FROM Books

答案 1 :(得分:1)

执行此操作的一种方法是首先将字符串拆分为单独的行,然后将其连接到另一个表,然后将其一起解析为相同的结构。

为了分割字符串,我建议使用Jeff Moden(http://www.sqlservercentral.com/articles/Tally+Table/72993/)的DelimitedSplit8k,最后的东西应该是这样的(现在不能测试,但希望它&#39) ;好的):

select b.id, b.title, d.Item as c 
into #tmp 
from books b cross apply dbo.DelimitedSplit8K(b.authors, ';') as d

select t2.id, t2.title, (SELECT STUFF(
             (SELECT ';' + a.name 
              FROM #tmp t1
              join authors a on a.id = t1.c
              where t1.id = t2.id
              FOR XML PATH (''))
             , 1, 1, '')) as Name
from (
  select distinct id, title from #tmp
) t2