0

I have a table that looks like this in MS SQL Server.

SQL Table

I want to query this table so that the TagId and Value columns are grouped together by EntityId and displayed as XML.

Sample query result

Sample Result

The XML structure is not fixed. Any type of XML structure will do. Is it possible?

Zuber
  • 577
  • 1
  • 11
  • 29
  • Almost everything is possible in SQL (it is [Turing complete language](https://stackoverflow.com/questions/7284/what-is-turing-complete)). If you post sample data https://dbfiddle.uk instead of pictures I could prepare solution(simple FOR XML) – Lukasz Szozda May 25 '18 at 09:54

2 Answers2

2

You could use:

SELECT o.EntityName,
       o.EntityId,
       (SELECT (SELECT i.TagId "Tag/@id",
                       i.Value "Tag/@value"
                       FROM elbat i
                       WHERE i.EntityId = o.EntityId
                       FOR XML PATH(''),
                               TYPE)
               FOR XML PATH('Tags')) Value
       FROM elbat o
       GROUP BY o.EntityName,
                o.EntityId;

SQL Fiddle

sticky bit
  • 36,626
  • 12
  • 31
  • 42
0

This not seems like a better method. But it gives solution:

DECLARE @Table TABLE(id int, TagId int, Entityname Varchar(100),EntityId INt, value VARCHAR(50))

INSERT INTO @Table VALUES(1,1,'TravelerProfile',856,'Finanace')
INSERT INTO @Table VALUES(2,2,'TravelerProfile',856,'A')
INSERT INTO @Table VALUES(3,3,'TravelerProfile',856,'pune')

 select
   distinct Entityname, EntityId,
    stuff((
        select ',' + 'OpenTag'+ CAST(u.id AS VARCHAR)+'MidTag'+ u.value+'EndTag'
        from @Table u
        where u.EntityId = EntityId
        order by u.EntityId
        for xml path('')
    ),1,1,'') as Value
INTO #temp
from @Table
group by Entityname,EntityId

SELECT Entityname, EntityId
    ,REPLACE(REPLACE(REPLACE(REPLACE(VALUE,'OpenTag','<Tags><TagId = "'),'MidTag','" value="'),'EndTag','"/></Tags>'),',','') Value
FROM #temp

DROP TABLE #temp

Output:

Entityname      EntityId    Value
TravelerProfile 856         <Tags><TagId = "1" value="Finanace"/></Tags><Tags><TagId = "2" value="A"/></Tags><Tags><TagId = "3" value="pune"/></Tags>
DineshDB
  • 5,998
  • 7
  • 33
  • 49