Search code examples
sqlsql-serverxmlselectsqlxml

Modifying XML Column with Select Query


I have a SQL Server table with a XML column which got information in. I want to select whole ID's from this table and modify my another xml column.

My query is;

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;

I'm getting

Msg 8172, Level 16, State 1, Line 5
The argument 1 of the XML data type method "modify" must be a string literal.

Any help would be nice.


Solution

  • Are you sure you want to put the whole xml into attribute of Information1, like this:

    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