【问题标题】:Modifying XML Column with Select Query使用选择查询修改 XML 列
【发布时间】:2013-10-15 01:38:24
【问题描述】:

我有一个带有 XML 列的 SQL Server 表,其中包含信息。我想从该表中选择整个 ID 并修改我的另一个 xml 列。

我的查询是;

declare @name nvarchar(max);
set @name = 'mark';

update table1 
set table1.Information1.modify('insert <s n="' + cast((select cast(table2.Information2 as varchar(100)) 
from table2 
where table2.Information2.exist('/r/s[@n=sql:variable("@name")]') = 1) as varchar(400)) + '"/> into (/r)[1]') where table1.Name = @name;

我明白了

消息 8172,第 16 级,状态 1,第 5 行
XML 数据类型方法“modify”的参数 1 必须是字符串字面量。

任何帮助都会很好。

【问题讨论】:

  • 示例数据和所需的输出会很好

标签: sql sql-server xml select sqlxml


【解决方案1】:

你确定要将整个xml放入Information1的属性中,像这样:

declare @name nvarchar(max), @data xml

select @name = 'mark'

select cast(Information2 as varchar(100)) as n
from table2 as t
where t.Information2.exist('/r/s[@n=sql:variable("@name")]') = 1
for xml raw('s')

update table1 set Information1.modify('insert sql:variable("@data") into (/r)[1]') 

sql fiddle demo

【讨论】:

    【解决方案2】:

    与过滤一样,您需要使用sql:variable。您不能在 .modify 函数中构建字符串。

    declare @newData xml    
    select @newData = '<s n="' + 
          cast(table2.Information2 as varchar(100)) 
           + '"/>' 
    from table2 
    where table2.Information2.exist('/r/s[@n=sql:variable("@name")]') = 1
    
    update table1 set Information1.modify('insert sql:variable("@newData") into (/r)[1]') 
    

    【讨论】:

    • 有了这个选择,我只得到了一行。与roman pekar的回答混合在一起,我得到了我需要的东西:)也感谢你!
    猜你喜欢
    • 2021-11-29
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多