加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

使用SQL Server XML数据类型

发布时间:2020-12-12 08:57:52 所属栏目:MsSql教程 来源:网络整理
导读:我有一个有 XML字段的表. 它包含的典型的XML是 things Fruit imageId39/imageId titleApple/title /Fruit Fruit imageId55/imageId titlePear/title /Fruit Fruit imageId76/imageId titleGrape/title /Fruit/things 在我的表中,我有大约50行,我只关心两个字
我有一个有 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

这是你要找的?

渣子

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读