简体   繁体   English

SQL解析XML列数据

[英]SQL Parse xml column data

I have very little experience with SQL Server. 我对SQL Server的经验很少。 Here is what I am trying to accomplish: 这是我要完成的工作:

I have a table with many rows. 我的桌子上有很多行。 Every row contains a column named "Config". 每行包含一个名为“ Config”的列。 The data stored in the Config column is of the xml type. 存储在“配置”列中的数据是xml类型。 The xml structure looks like this: xml结构如下所示:

<root>
 <path1>
  <path2>
   <path3>true</path3>
  </path2>
 </path1>
</root>

I am trying to go through every row in the table and find the percentage of true to false values of <path3> . 我试图遍历表中的每一行,并找到<path3>truefalse值的百分比。

I looked at some SQL documentation and tried to use the value() function I am having difficulties extracting the XML data from the column: 我查看了一些SQL文档,并尝试使用value()函数,但是我很难从列中提取XML数据:

select Config.value('(/root/path1/path2/path3)[1]','nvarchar(max)') from [MyDB].[dbo].[MyTable]

Here is the result of my query: 这是我的查询结果:

执行以上语句后的SQL查询结果

I would like to query and extract data from the XML "Config" column of my table and aggregate that data into columns. 我想从表的XML“ Config”列中查询和提取数据,并将该数据聚合到列中。

You need to specify namespaces in the query when xml is built with namespaces. 使用名称空间构建xml时,需要在查询中指定名称空间。 For example 例如

CREATE TABLE tbl (Config xml);
INSERT INTO tbl (Config)
VALUES ('<root xmlns="abc">
 <path1>
  <path2>
   <path3>true</path3>
  </path2>
 </path1>
</root>') ;

Then 然后

with xmlnamespaces (DEFAULT 'abc')
select Config.value('(/root/path1/path2/path3)[1]','nvarchar(max)') path3Txt
from tbl;

or explicit specification 或明确的规范

with xmlnamespaces ('abc' as x)
select Config.value('(/x:root/x:path1/x:path2/x:path3)[1]','nvarchar(max)') path3Txt
from tbl;

You would need to use CROSS APPLY. 您将需要使用CROSS APPLY。 Check it out. 看看这个。

SQL 的SQL

-- DDL and sample data population, start

    DECLARE @tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, [Config] XML);
    INSERT INTO  @tbl
    VALUES (N'<root>
        <path1>
            <path2>
                <path3>true</path3>
            </path2>
        </path1>
    </root>')
    , (N'<root>
        <path1>
            <path2>
                <path3>false</path3>
            </path2>
        </path1>
    </root>');
    -- DDL and sample data population, end

    ;WITH rs AS
    (
       SELECT ID
          , col.value('(./text())[1]','VARCHAR(20)') AS Result
        FROM @tbl tbl
          CROSS APPLY tbl.[Config].nodes('/root/path1/path2/path3') AS tab(col)
    )
    SELECT * FROM rs;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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