【问题标题】:XML question in SQL ServerSQL Server 中的 XML 问题
【发布时间】:2009-06-01 22:05:50
【问题描述】:

在我的一个 sql 脚本中,我需要使用以下 xml 字符串执行存储过程

<Collection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Field>
        <Attributes>
            <Attribute Name="CODE1" IsRequired="true" Order="1" IsVisible="true"/>
            <Attribute Name="CODE2" IsRequired="true" Order="2" IsVisible="true"/>
        </Attributes>
        <Rows>
            <Row ProductState="5">
                <Items>
                    <Item Name="PROD1" SendCustomer="false"/>
                    <Item Name="PROD2" SendCustomer="false"/>
                </Items>
            </Row>
        </Rows>
    </Field>
</Collection>

我从不同的表中获得AttributeItem 信息。我正在编写一个通用函数,您可以在其中传递一个 ID 并返回 SQL 脚本用来执行存储过程的 XML 字符串

有时,我需要覆盖一些元素的属性值,例如SendCustomer。我最初的想法是将其反序列化为临时表,使用覆盖值更新临时表,然后将其序列化回 XML。

所以,基本上,整个过程归结为:

  1. 查询表,在函数中序列化为XML
  2. 反序列化 XML,存储在临时表中
  3. 必要时覆盖值
  4. 再次从表序列化为 XML

在 sql server 2005 中是否有更优雅的方式来完成整个过程?

【问题讨论】:

    标签: sql-server xml sql-server-2005


    【解决方案1】:

    XML 数据类型实际上可以使用 XQuery 进行修改。见the modify() method

    declare @x XML;
    select @x = N'<Collection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <Field>
            <Attributes>
                    <Attribute Name="CODE1" IsRequired="true" Order="1" IsVisible="true"/>
                    <Attribute Name="CODE2" IsRequired="true" Order="2" IsVisible="true"/>
            </Attributes>
            <Rows>
                    <Row ProductState="5">
                            <Items>
                                    <Item Name="PROD1" SendCustomer="false"/>
                                    <Item Name="PROD2" SendCustomer="false"/>
                            </Items>
                    </Row>
            </Rows>
        </Field>
    </Collection>';
    
    set @x.modify(N'replace value of 
        (/Collection/Field/Rows/Row/Items/Item[@Name="PROD2"]/@SendCustomer)[1]
        with "true"');
    
    select @x;
    

    【讨论】:

    • 你能解释一下 JQuery 解决方案如何适应我的问题吗?谢谢
    • 什么是 JQuery?我的答案是 Transact-SQL。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多