Rows to comma separated values using XML tag

前端 未结 1 1460
说谎
说谎 2020-12-22 10:14

I have 2 tables named \'Categories\' and \'CSTagContent\' shown below with data...

TABLE 1: \'Categories\'

CategoryID  PostID  <-         


        
相关标签:
1条回答
  • 2020-12-22 11:14

    SAMPLE TABLES

    SELECT * INTO Categories
    FROM
    (
       SELECT 1148 CategoryId, 581771 PostId
       UNION ALL
       SELECT 1183 CategoryId, 581771 PostId
       UNION ALL
       SELECT 1184 CategoryId, 581771 PostId   
    )TAB
    
    
    SELECT * INTO TagContent
    FROM
    (
    SELECT 1 [Id], '<blockquote><p><a href="abc.com"></p></blockquote>' TagContent ,    '2014-11-08' StartDate, '2014-11-14' EndDate,  1148 CategoryID, NULL TagTitle     
    
    UNION ALL   
    SELECT  2, '<blockquote><p><a href="abc.com"></p></blockquote>',     '2014-11-25', '2014-12-05',  1183,     '<h1>Aging Title</h1>' 
    
    
    UNION ALL
    SELECT  3, '<blockquote><p><a href="abc.com"></p></blockquote>',     '2014-11-25', '2014-11-27',  1184,     '<h1>Allergies Title</h1>' 
    )TAB
    

    Now we convert TagTitle to Ambersand seperated valuesfor the same TagContent. Since XML format is used we need to replace &gt, &lt and&ampto <, > and &.

    QUERY

    SELECT DISTINCT TagContent,STUFF(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(
            (SELECT '&' + TagTitle
            FROM TagContent T2 
            WHERE ST.TagContent=T2.TagContent 
            FOR XML PATH('')),2,200000),'&lt;','<'),'&gt;','>'),'&amp;','&'),'amp;',''),1,'') TagTitle
            FROM Categories CPC
            JOIN TagContent ST ON CPC.CategoryId=ST.CategoryId
    
    • SQL FIDDLE
    0 讨论(0)
提交回复
热议问题