微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用SQL Server XML数据类型

我有一个XML字段的表.
它包含的典型的XML是
<things>
  <Fruit>
    <imageId>39</imageId>
    <title>Apple</title>
  </Fruit>
  <Fruit>
    <imageId>55</imageId>
    <title>Pear</title>
  </Fruit>
  <Fruit>
    <imageId>76</imageId>
    <title>Grape</title>
  </Fruit>
</things>

在我的表中,我有大约50行,我只关心两个字段,omId(int primary key)和omText(我的xml数据).

我想要实现的是一种说法,在整个表中的所有xml数据中…给我所有的标题为X的xmlElements或给我一个使用imageId为55的所有项目的计数.

我正在使用XML数据类型VALUE和QUERY函数来检索数据.

select omID,omText.query('/things/Fruit'),cast('<results>' + cast(omText.query('/things/Fruit') as varchar(max)) + '</results>' as xml) as Value
   from dbo.myTable
   where omText.value('(/things/Fruit/imageId)[1]','int') = 76

哪个只在我正在搜索的id是文档中的第一个.它似乎没有搜索所有的xml.

从根本上说,结果集返回了TABLE中每个条目的一行,我认为我需要为每个匹配的ELEMENT有一行…不完全确定如何开始为这个文件一个组.

我开始感觉到我正在努力使其变得比它需要的更难……想法和想法

解决方法

What i’m trying to achieve is a way of saying,across all
xml data in the whole table… give me all of the xmlElements
where the title is X.

不知道我是否完全理解你的问题 – 还是在寻找这个?您将抓住所有/ things / Fruit元素的“节点”,并将它们与myTable中的“基本数据”交叉连接 – 结果将是XML数据字段中每个XML元素的一行:

select 
   omID,T.Fruit.query('.')
from 
   dbo.myTable
cross apply
   omText.nodes('/things/Fruit') as T(Fruit)
where 
   T.Fruit.value('(title)[1]','varchar(50)') = 'X'

Or give me a count of all items that use an imageId of 55.

select 
   count(*)
from 
   dbo.myTable
cross apply
   omText.nodes('/things/Fruit') as T(Fruit)
where 
   T.Fruit.value('(imageId)[1]','int') = 55

这是你要找的?

渣子

原文地址:https://www.jb51.cc/mssql/74728.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐