小编典典

使用SQL在XML中插入节点

sql

我有以下XML:

create table #temp(cid int,xml_data xml)
insert into cid
values(1001,
     '<Main>
        <name>''John doe''</name>
        <age>15</age>
    </Main>')

我想基于简单的参数条件向此XML添加一个附加节点:

所需的输出:

<Main>
    <name>John doe</name>
    <type>Q</type>
    <age>15</age>
</Main>

代码:

select case when @type = 'Q' then
    UPDATE #temp
    SET Main.modify('insert <type = 'Q'> into 
        (/Main)')
    GO

我收到语法错误。任何帮助!

更新:

我在代码中实现了建议的解决方案,但出现错误。错过了一些愚蠢的东西!

 UPDATE #temp
         SET xml_data = 
            case
                when @type = 'G' 
                then xml_data.modify('insert <type>G</type> into (/Main)[1]');
                when @type = 'Q' 
                then xml_data.modify('insert <type>Q</type> into (/Main)[1]'); end

我收到“ XML数据类型方法的错误使用”修改”。在这种情况下,期望使用非突变方法。” 错误


阅读 149

收藏
2021-05-16

共1个答案

小编典典

无需任何复杂的麻烦。只需插入所需的节点即可:

UPDATE #temp SET xml_data.modify('insert <type>Q</type> into (/Main)[1]');

使用as firstas lastbefore / after允许您指定节点的位置。以下将新节点直接放置在<name>

UPDATE #temp SET xml_data.modify('insert <type>Q</type> after (/Main/name)[1]');

UPDATE有关更新语句的问题

您的陈述有几个缺陷:

UPDATE #temp
     SET xml_data =
        case
            when @type = 'G'
            then xml_data.modify('insert <type>G</type> into

(/Main)[1]’);
when @type = ‘Q’
then xml_data.modify(‘insert Q into
(/Main)[1]’);
end

您不能使用语法SET xmlColumn = xmlColumn.modify()。您必须使用SETxmlColumn.modify(),而且分号还是反而打破了这一点。

老实说,我认为这很复杂,请尝试以下操作:

DECLARE @type VARCHAR(1)='Q'
UPDATE #temp SET xml_data.modify('insert <type>{sql:variable("@type")}</type> into (/Main)[1]');

这将创建一个新节点<type>content</type>,其内容将从变量中取出@type

2021-05-16