从存储在SQL表中的XML字符串中提取多个值

时间:2019-01-16 16:06:33

标签: sql sql-server ssms

尝试从其值为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>

我怎么得到这样的结果:

Monday true
Wednesday true
Friday true 

我尝试使用Substring和Charindex,但这只能获得第一行。

谢谢。

2 个答案:

答案 0 :(得分:2)

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   |
+-----------+---------+

如果表具有多行,则应试一下季节-在这种情况下,您需要提取另一个值(WeeksInterval@t.ID?)以进一步区分结果。

答案 1 :(得分:1)

这是使用Nodes()

的简单示例

我不确定您是否只需要TRUE值

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)

返回

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