【问题标题】:Query multiple XML values查询多个 XML 值
【发布时间】:2012-03-27 14:25:24
【问题描述】:
<book>
<author>Bob Villa</author>
<author>Tom Whatever</author>
<author>Sarah kajdl</author>
</book>

我将如何查询任何具有 Tom What 作者的记录?我见过的大多数查询示例都引用了值 [x],但我想搜索所有作者。

DECLARE @author as varchar(100)
SET @author = 'Tom Whatever'
SELECT xmlfield.value('/book/author')
WHERE xmlfield.value('/book/author') = @author

【问题讨论】:

    标签: sql-server xml


    【解决方案1】:

    这就是答案

    DECLARE @x XML 
    SET @x = '<book>
    <author>Bob Villa</author>
    <author>Tom Whatever</author>
    <author>Sarah kajdl</author>
    </book>'
    
    DECLARE @author AS VARCHAR(100)
    SET @author = 'Tom Whatever'
    SELECT c.value('.' ,'VARCHAR(100)')
    FROM   @x.nodes('book/author') AS t(c)
    WHERE   c.value('.' ,'VARCHAR(8000)') = @author
    

    【讨论】:

    【解决方案2】:

    如果您只想要 XML 变量的值,您可以直接使用 value 方法并在 XPath 表达式中使用 sql:variable

    SELECT @XML.value('(/book/author[.=sql:variable("@author")])[1]', 'nvarchar(50)')
    

    如果您将 XML 放在一个表中并且想要有作者的行,您可以使用exist

    select *
    from YourTable
    where XMLCol.exist('/book/author[.=sql:variable("@author")]') = 1
    

    然后你当然可以将它们组合起来。

    select XMLCol.value('(/book/author[.=sql:variable("@author")])[1]', 'nvarchar(50)')
    from YourTable
    where XMLCol.exist('/book/author[.=sql:variable("@author")]') = 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多