【问题标题】:Querying XML field in database table using SQL使用 SQL 查询数据库表中的 XML 字段
【发布时间】:2017-02-25 11:00:56
【问题描述】:

我有一个名为 VehicleHistoryBlob 的表,其结构如下:

VehicleHistoryBlobId int PRIMARY KEY
VehicleHistoryBlob XML

我需要编写 SQL 来查找 VehicleHistoryBlob XML 中的所有条目,这些条目具有 Bus 作为父节点,Destination 作为子节点(Bus 可以有多个 Destination,并且 XML 中的父节点并不总是 Bus)。

<Bus>
...
    <Destination>
            <Name>The big building</Name>
            <DestinationCode> A21301423 </DestinationCode>
            <DestinationAddress> 440 Mountain View Parade </DestinationAddress>
            <DestinationCountry> USA </DestinationCountry>
    </Destination>
</Bus>'

我需要通过 XML 进行查询并找到所有以 Bus 作为父节点和 Destination 作为子节点的条目,并将与 XML 关联的 VehicleHistoryBlobId 传递到我的临时表 @tmpTable

DECLARE @tmpTable TABLE(theints INT)

我一直在尝试操作 .nodes 函数,但由于我缺乏将 XML 作为数据类型的经验,我很难获得准确的结果。

提前致谢!

【问题讨论】:

    标签: sql sql-server xml database tsql


    【解决方案1】:

    要在 XML 列上按特定条件过滤行,您可以使用 exist() 方法而不是 nodes()。例如,以下查询插入到 @temptable VehicleHistoryBlobId,其中对应的 XML 有 Bus 作为根元素和 Destination 子元素:

    INSERT INTO @tmpTable
    SELECT v.VehicleHistoryBlobId 
    FROM VehicleHistoryBlob v
    WHERE v.VehicleHistoryBlob.exist('/Bus/Destination') = 1
    

    sqlfiddle demo

    【讨论】:

    • 太棒了!非常感谢@har07
    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多