sqlserver如何操作xml
1、创建一个product.xml文件,如下:
<products>
<product id="1">
<name>A产品</name>
<price>23.5</price>
<qty>34</qty>
</product>
<product id="2">
<name>B产品</name>
<price>23.5</price>
<qty>34</qty>
</product>
<product id="3">
<name>C产品</name>
<price>23.5</price>
<qty>34</qty>
</product>
</products>

2、打开查询分析器,创建一个存储xml文件的表
create table xmlTest(xmlStr xml)
注意字段格式为xml

3、将我们的product.xml文件数据导入到该表
bulk
insert xmlTest from 'd:/backup/product.xml'
with (
DATAFILETYPE ='widechar',
ROWTERMINATOR='' --默认为/n换行,我们这里不需要换行
)
然后查询结果
select * from xmlTest


1、xml的查询在sql中都是按照路径查询的,路径有相对路径和绝对路径
例如我们要查询product节点id=1的name节点,查询分析器中输入如下语句:select xmlStr.query('//product[@id=1]/name') from xmltest
以上就是一个相对查询 使用//开始,其下为输出结果

2、我们再使用绝对路径来查询product节点id=1的name节点,输入以下语句:
select xmlStr.query('/products/product[@id=1]/name') from xmltest
可以看到其结果和上面的查询是一样的

1、xml的值的查询使用value方法,例如我们查询product节点id=1的name节点的值,可以在查询分析器中输入
select xmlStr.value('(/products/product[@id=1]/name)[1]','varchar(max)') from xmltest
或者使用相对路径查询使用以下语句:
select xmlStr.value('(//product[@id=1]/name)[1]','varchar(max)')
from xmltest
输出结果如下
注意:以上语句需要加上一个返回值的类型,

1、如果我们需要添加一个节点,可以使用modify方法,例如我们需要在第三个product的后面加个product其id等于4,那么可以在查询分析器中输入以下语句
update xmlTest
set xmlStr.modify('insert <product id="4">
</product> after(/products/product)[3]')
after 表示在某个节点后添加节点
before表是在某个节点前添加节点

2、再在<product id=4></product>中加入子节点 ,例如添加一个name
update xmlTest
set xmlStr.modify('insert <name>G产品</name> into(/products/product)[4]')
以此类推我们就添加完了产品信息了
注:这里的into 表示将某个节点插入某个节点里面

1、修改xml 使用modify方法中的replace value of text with newTest,翻译过来就是用某个新的文本代替以前的文本,product中name的值,可以输入以下语句:
update xmlTest
set xmlStr.modify('replace value of (//product/name/text())[1] with "修改后的产品"')
输出结果如下

1、将xml导出成文件,可以参考我以前写的将表数据导出成xls文件这篇经验,这里就不再赘述了,以下为参考地址:
https://jingyan.baidu.com/article/3ea514891bb18113e61bba9f.html