简体   繁体   中英

Extracting mutiple values from an XML string stored in a SQL table

Trying to extract data from a column whose values are in XML like below which lists when a report runs during the week:

WeeklyRecurrence <WeeksInterval>1</WeeksInterval><DaysOfWeek><Sunday>false</Sunday><Monday>true</Monday><Tuesday>false</Tuesday><Wednesday>true</Wednesday><Thursday>false</Thursday><Friday>true</Friday><Saturday>false</Saturday></DaysOfWeek></WeeklyRecurrence>

how would I get to a result like:

Monday true
Wednesday true
Friday true 

I have tried using Substring and Charindex but this am only able to get the 1st row.

Thanks in advance.

DECLARE @t TABLE(schedule XML);
INSERT @t(schedule) VALUES (N'<WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Sunday>false</Sunday><Monday>true</Monday><Tuesday>false</Tuesday><Wednesday>true</Wednesday><Thursday>false</Thursday><Friday>true</Friday><Saturday>false</Saturday></DaysOfWeek></WeeklyRecurrence>');

SELECT 
    [day] = x.value('local-name(.)', 'nvarchar(max)'),
    [present] = x.value('.', 'nvarchar(max)')
FROM @t 
CROSS APPLY schedule.nodes('/WeeklyRecurrence/DaysOfWeek/*') w(x)
+-----------+---------+
|    day    | present |
+-----------+---------+
| Sunday    | false   |
| Monday    | true    |
| Tuesday   | false   |
| Wednesday | true    |
| Thursday  | false   |
| Friday    | true    |
| Saturday  | false   |
+-----------+---------+

Season to taste if the table has multiple rows -- you'll need to extract another value ( WeeksInterval ? @t.ID ?) to distinguish the results further in this case.

Here's a quick example of using Nodes()

I'm not sure if you wanted just the TRUE values

Declare @XML xml = '<WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Sunday>false</Sunday><Monday>true</Monday><Tuesday>false</Tuesday><Wednesday>true</Wednesday><Thursday>false</Thursday><Friday>true</Friday><Saturday>false</Saturday></DaysOfWeek></WeeklyRecurrence>'

Select Item  = xAttr.value('local-name(.)', 'nvarchar(100)')
      ,Value = xAttr.value('.','varchar(100)')
From  @XML.nodes('//WeeklyRecurrence/DaysOfWeek/*') xNode(xAttr)

Returns

Item        Value
Sunday      false
Monday      true
Tuesday     false
Wednesday   true
Thursday    false
Friday      true
Saturday    false

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