简体   繁体   English

将具有属性的XML元素插入SQL XML列

[英]Insert XML element with attribute into SQL XML column

I have the following XML data stored in [MyTable].Column1 which is an XML type column. 我将以下XML数据存储在[MyTable].Column1 ,这是XML类型列。

在此处输入图片说明

I want to insert a new element to it: 我想向其中插入一个新元素:

在此处输入图片说明

I'm using the following SQL, it executed successfully but when I query the same column value again, I do not see my new XML element. 我正在使用以下SQL,它已成功执行,但是当我再次查询相同的列值时,看不到新的XML元素。 Do I miss certain syntax for inserting an element with attributes? 我会错过某些带有属性的元素插入的语法吗?

UPDATE [MyTable] 
SET Column1.modify('insert <Setting Name="H" Value="0"/> as last into (/SettingValues)[1]')
WHERE ID = 'xxxxx' 

First of all - for your next question: Please do not post pictures! 首先-关于下一个问题:请不要发布图片! Try to set up a test-scenario. 尝试设置一个测试方案。 Please read How to ask a good SQL question and How to create a MCVE . 请阅读如何提出一个好的SQL问题以及如何创建MCVE

About your question 关于你的问题

Your code - on the first sight - should work. 您的代码-乍一看-应该可以工作。 But you obviously modified it to fit to this forum. 但是您显然已对其进行了修改,以适合该论坛。

DECLARE @myTable TABLE(ID VARCHAR(100),Column1 XML)
INSERT INTO @myTable VALUES
 ('111'
  ,'<SettingValues>
     <Setting Name="A-name" Value="A-value"/>
   </SettingValues>')
, ('222'
  ,'<SettingValues>
     <Setting Name="A-name" Value="A-value"/>
   </SettingValues>');

UPDATE @MyTable 
SET Column1.modify('insert <Setting Name="H" Value="0"/> as last into (/SettingValues)[1]')
WHERE ID = '222';

SELECT * 
FROM @myTable

This works as expected. 这按预期工作。

ID  Column1
111 <SettingValues><Setting Name="A-name" Value="A-value" /></SettingValues>
222 <SettingValues><Setting Name="A-name" Value="A-value" /><Setting Name="H" Value="0" /></SettingValues>

After execution you see "1 row affected". 执行后,您会看到“受影响的第一行”。

Some ideas: 一些想法:

  • The filter is not fullfilled 过滤器未满
  • The given XML declares namespaces but never uses them... This is a bit odd. 给定的XML声明了名称空间,但从未使用过它们。这有点奇怪。 Have you reduced the namespaces and your original XML includes a default namespace (or the elements are prefixed somehow)? 您是否减少了名称空间,并且原始XML包含默认名称空间(或者以某种方式为元素添加了前缀)?
  • You are checking against the wrong target (other server, other schema, other table... 您正在检查错误的目标(其他服务器,其他架构,其他表...

But: The code above should work... 但是:上面的代码应该工作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM