【问题标题】:Find if element exists in XML column of a SQL Server table查找 SQL Server 表的 XML 列中是否存在元素
【发布时间】:2015-12-09 00:44:40
【问题描述】:

我已将数据序列化为 SQL Server 表中的 XML 列,格式如下:

<Form title="Sample Data">
  <MyProperty>1234</MyProperty>
  <Employee>
     <MyProperty>1234</MyProperty>
  </Employee>
</Form>

元素MyProperty 可以位于根级别,也可以是&lt;Employee&gt; 下的子元素。

我需要的是一个 SQL 脚本:

  1. 检查MyProperty 是否存在于 XML 的根级别(我不关心它的子版本)
  2. 如果不存在,则在根级别插入记录。

MyProperty 的值之前已经计算过了,我打算将它连同具有序列化 XML 的行的 PK 一起放入一个临时表中。

任何人都可以就如何做到这一点提供一些指导吗?

【问题讨论】:

  • 请一次一个问题,尤其是当您不知道从哪里开始或如何开始时。你首先想达到什么目标?我假设:“检查 MyProperty 是否存在于 XML 的根级别”。阅读exist() 方法并尝试为您的案例实施它

标签: sql-server xml


【解决方案1】:

第一个问题可以使用如下所示的简单 XPATH 语法来回答。

declare @x xml = '<Form title="Sample Data">
  <MyProperty>1234</MyProperty>
  <Employee>
     <MyProperty>1234</MyProperty>
  </Employee>
</Form>';


--does MyProperty exist at the root level?
declare @rootlevelvalue nvarchar(max) = (select T.c.value('(MyProperty)[1]','nvarchar(max)') from @x.nodes('/Form') T(c));
if @rootlevelvalue is not null
begin
  print 'yes, it exists at the root level (value = ' + @rootlevelvalue + ')';
end
else
begin
  print 'no, it does not exist at the root level'
end

第二个问题可以用 XPATH 的 insert 语法来回答。

declare @y xml = '<Form title="Sample Data">
  <Employee>
     <MyProperty>1234</MyProperty>
  </Employee>
</Form>';


--does MyProperty exist at the root level?
declare @rootlevelvalue nvarchar(max) = (select T.c.value('(MyProperty)[1]','nvarchar(max)') from @y.nodes('/Form') T(c));
if @rootlevelvalue is not null
begin
  print 'yes, it exists at the root level (value = ' + @rootlevelvalue + ')';
end
else
begin
  print 'no, it does not exist at the root level';
  set @y.modify('insert <MyProperty>99999</MyProperty>into (/Form)[1]')
  print 'so we added it.';
end
select @y

【讨论】:

  • 谢谢,关于第一部分:我使用 .exist() 来检查 har07 建议的 XML 中是否存在该元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2010-09-11
  • 1970-01-01
  • 2010-09-13
相关资源
最近更新 更多