在表格中显示数据

时间:2013-11-29 11:53:55

标签: sql sql-server xml sql-server-2008-r2 sqlxml

目标:
在自定义表格中显示xml的数据。

请求的表格列表将是

user         firstname     lastname     hour    projectname      sex
-------------------------------------------------------------------------
userTime     sara          brown        20      null             null
userProject  jessica       black        null    Melissa          null
userProject  Jim           west         null    Sakura   null
userSex      robert        lake         null    null             male

等...

问题:
在hiearchy我有三个不同的层次

<userTime>, <userProject> and <userSex>

是它的子集,我希望它们和其他列在自定义表格中显示,其时间顺序与xml数据类似。

信息:
* XML中userTime,userProject和userSex的数据是随机的 * XML中的列表很大。

 DECLARE @xml XML
 SET @xml =
 (
         SELECT * FROM OPENROWSET
         (
                 BULK 'C:\server\xml\test.xml', SINGLE_CLOB
         ) AS xmlData
 )

 SELECT
         firstname = Events.value('(firstname)[1]', 'VARCHAR(100)'),
         lastname = Events.value('(lastname)[1]', 'VARCHAR(100)'),
         hour = Events.value('(hour)[1]', 'VARCHAR(100)')                                                                            
 FROM @XML.nodes('/users/userTime') as XTbl(Events)

<users>
    <userTime>
        <firstname>sara</firstname>
        <lastname>brown</lastname>
    <hour>20</hour>
    </userTime>
    <userProject>
        <firstname>jessica</firstname>
        <lastname>black</lastname>
        <projectname>Melissa</projectname>
    </userProject>
    <userProject>
        <firstname>Jim</firstname>
        <lastname>west</lastname>
        <projectname>Sakura</projectname>
    </userProject>
    <userSex>
        <firstname>robert</firstname>
        <lastname>lake</lastname>
        <sex>male</sex>
    </userSex>
    <userTime>
        <firstname>Britany</firstname>
        <lastname>lake</lastname>
    <hour>20</hour>
    </userTime>
    <userTime>
        <firstname>sara</firstname>
        <lastname>brown</lastname>
    <hour>20</hour>
    </userTime>
</users>

1 个答案:

答案 0 :(得分:1)

select
    t.c.value('local-name(.)', 'nvarchar(max)') as [user],
    t.c.value('(firstname/text())[1]', 'nvarchar(max)') as firstname,
    t.c.value('(lastname/text())[1]', 'nvarchar(max)') as lastname,
    t.c.value('(hour/text())[1]', 'nvarchar(max)') as hour,
    t.c.value('(projectname/text())[1]', 'nvarchar(max)') as projectname,
    t.c.value('(sex/text())[1]', 'nvarchar(max)') as sex
from @XML.nodes('users/*') as t(c)

<强> sql fiddle demo

SQL Server - using XPath Queries