sqlserver2005 xml字段的读写操作
时间:2024-01-16 23:00:37
1.创建xml字段
在表xmlTest内创建一个字段,命名_x,设置数据类型为xml。
2.写入xml
insert into xmlTest (_x) values('
<root>
<item attr1="a1" attr2="a2">item11</item>
<item attr1="a1" attr2="a2">item12</item>
</root>
')
go
如此再插入一条记录:
insert into xmlTest (_x) values('
<root>
<item attr1="b1" attr2="b2">item21</item>
<item attr1="b1" attr2="b2">item22</item>
</root>
')
3.查询数据
3.1 查询字段所有数据
select _x from xmlText
结果如图:
3.2 查询root下面的第一个item节点
select _x.query('root/item[1]')
from xmlTest
结果:
3.3 查询root下面的第一个item节点的值
select _x.value('(root/item)[1]','varchar(50)')
from xmlTest
结果:
3.3 查询root下面的第二个item节点的attr2属性值
select _x.value('(root/item/@attr2)[2]','varchar(50)')
from xmlTest
结果:
3.4 查询表中每条记录的xml字段的item节点值,全部列出来
SELECT t2.c1.value('.','varchar(20)') as items
from xmlTest
cross apply _x.nodes('root/item') as t2(c1)
结果:
3.5 查询表中id=1记录的xml的所有item字段的attr2属性值
SELECT t2.c1.value('@attr2','varchar(20)') as attr2
from xmlTest
cross apply _x.nodes('root/item') as t2(c1)
where id='1'
结果:
3.6 查询id为1的所有节点中attr1属性为a1的第一个匹配节点的attr2属性值
select _x.value('(root/item[@attr1="a1"]/@attr2)[1]','varchar(50)')
from xmlTest where id='1'
结果:
3.7 多表查询
例如:存在另外1个table:t2,其字段xmlid关联表xmlTest,而attr1关联xmlTest的_x字段中的attr1属性值。
查询表xmlTest中id=‘1'记录中_x字段内item节点中attr1为表t2中attr1字段值时,item节点中attr2的属性值
select xmlTest._x.value('(root/item[@attr1=sql:column("t2.attr1")]/@attr2)[1]','varchar(50)') as attr2,t2.attr1
from xmlTest join t2 on t2.xmlid=xmlTest.id
where xmlTest.id='1'
4.修改数据
4.1 修改表中id=1记录的第一个item节点值
UPDATE xmlTest
set _x.modify('replace value of (root/item/text())[1] with "xxxxx"')
where id='1'
select _x.query('root/item[1]') as item1
from xmlTest
结果:
4.2 修改表中id=2记录的第二个item节点的attr2属性值
UPDATE xmlTest
set _x.modify('replace value of (root/item/@attr2)[2] with "2222b"')
where id='2'
select _x.query('root/item[2]') as item1
from xmlTest
结果:
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python绘制3d螺旋曲线图实例代码
![](https://img.aspxhome.com/file/2023/9/75209_0s.png)
Python中Yield的基本用法
python调用api实例讲解
完美解决torch.cuda.is_available()一直返回False的玄学方法
![](https://img.aspxhome.com/file/2023/8/128218_0s.jpg)
Oracle不同数据库间对比分析脚本
oracle 存储过程和触发器复制数据
在keras中获取某一层上的feature map实例
![](https://img.aspxhome.com/file/2023/3/101113_0s.jpg)
go如何删除字符串中的部分字符
![](https://img.aspxhome.com/file/2023/8/123908_0s.png)
Python离线安装包教程分享
![](https://img.aspxhome.com/file/2023/4/127704_0s.jpg)
Vue+Java+Base64实现条码解析的示例
GIT相关-IDEA/ECLIPSE工具配置的教程详解
![](https://img.aspxhome.com/file/2023/9/132359_0s.png)
sqlserver中将varchar类型转换为int型再进行排序的方法
MySQL数据库事务transaction示例讲解教程
![](https://img.aspxhome.com/file/2023/0/119720_0s.png)
python中HTMLParser模块知识点总结
python导入时小括号大作用
浅析Python 中整型对象存储的位置
python matplotlib中的subplot函数使用详解
![](https://img.aspxhome.com/file/2023/3/67813_0s.jpg)
python3 常见解密加密算法实例分析【base64、MD5等】
Pytorch 使用tensor特定条件判断索引
![](https://img.aspxhome.com/file/2023/8/121158_0s.jpg)