简体   繁体   中英

T-SQL XML: How do I get my results in the format listed below?

This is my first time here. I need to get my XML formatted in the following format:

<Summary Year="2018" QtrNum="1" WeekNum="4" Date="1/22/2018" Code="101">

Once I get it to this format, then I need this XML generated for each row of my table. Here is a screenshot of the expected result set.

Expected Result Set

Thank you in advance.

Although your question is rather unclear, my magig crystal ball tells me, that you might be looking for something like this:

DECLARE @someTable TABLE(SomeDate DATE, SomeQrt INT, SomeWeek INT, SomeCode INT);
INSERT INTO @someTable VALUES('20180122',1,4,101);

DECLARE @SomeRelatedTable TABLE(SomeText VARCHAR(100),SomeCode INT);
INSERT INTO @SomeRelatedTable VALUES('Row 1',101)
                            ,('Row 2',101)
                            ,('Other code',999);

SELECT YEAR(t.SomeDate) AS [@Year]
      ,t.SomeQrt AS [@QrtNum]
      ,t.SomeWeek AS [@WeekNum]
      ,t.SomeDate AS [@Date]
      ,t.SomeCode AS [@Code]
      ,(
        SELECT SomeText AS [@InnerText]
        FROM @SomeRelatedTable rt
        WHERE rt.SomeCode=t.SomeCode
        FOR XML PATH('InnerNode'),TYPE
       )
FROM @someTable t           
FOR XML PATH('Summary');

The result

<Summary Year="2018" QrtNum="1" WeekNum="4" Date="2018-01-22" Code="101">
  <InnerNode InnerText="Row 1" />
  <InnerNode InnerText="Row 2" />
</Summary>           

Some Explanation

FOR XML PATH allows full control over the XML generation through the column's alias and PATH / ROOT extension.

The related (inner) nodes are created with a correlated sub-query.

I was able to solve my problem. Look at the scenario below.

drop table #test
create table #test(id int identity(1,1),locationcode varchar(6),businessdate date, quarternum int, weeknum int)

insert into #test(locationcode,businessdate, quarternum, weeknum)
values('000001',GETDATE(),2,2),
('000001',GETDATE(),2,2),
('000002',GETDATE(),2,2),
('000003',GETDATE(),2,2),
('000004',GETDATE(),2,2),
('000005',GETDATE(),2,2),
('000006',GETDATE(),2,2),
('000007',GETDATE(),2,2)

SELECT 
    (SELECT YEAR(b.businessdate) AS '@Year',b.QuarterNum AS '@QtrNum',b.WeekNum AS '@WeekNum',FORMAT(b.BusinessDate,'MM/DD/YYYY') AS '@Date'
                ,b.LocationCode  AS '@Code' 
     FROM #test c where b.id = c.id FOR XML PATH('DailySummary'),TYPE) AS Row
FROM #test b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM