【问题标题】:TSQL where on xml data typeTSQL where on xml 数据类型
【发布时间】:2012-07-11 10:03:00
【问题描述】:

如何在 Sql Server 2005 中对 xml 数据类型执行 where 子句命令?

Xml 结构

<User UserId="1" UserName="x">
<User UserId="2" UserName="y">

查询

SELECT XmlColumn from Table where XmlColumn.query('/User[@UserId'+ @dynamicValue +']')

预期输出

获取属性UserId=输入变量的所有用户标签

【问题讨论】:

    标签: xml tsql where-clause


    【解决方案1】:
    declare @T table
    (
      XMLColumn xml
    )
    
    insert into @T values ('<User UserId="1" UserName="x"/>')
    insert into @T values ('<User UserId="2" UserName="y"/>')
    
    declare @UserID int
    set @UserID = 1
    
    select XMLColumn
    from @T
    where XMLColumn.exist('/User[@UserId = sql:variable("@UserID")]') = 1
    

    结果:

    XMLColumn
    ---------------------------------
    <User UserId="1" UserName="x" />
    

    【讨论】:

    • +1 使其易于理解。顺便说一句,有没有涉及 SqlVariable 的解决方案
    • 如果你想有一个动态的方式来指定用户ID。您当然可以动态构建语句并使用sp_executesql
    猜你喜欢
    • 2020-06-15
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多