-- 作者:admin
-- 发布时间:2008/2/20 15:23:10
-- [推荐]XML学习资料之五——SQL Server2000对XML的支持
1、简单使用 使用标签属性显示全部节点 select * from stu for xml auto
使用XML标签显示全部节点 select * from stu for xml auto,ELEMENTS
显示schema信息 select * from stu for xml auto,XMLDATA,ELEMENTS
注意:要想显示全部结果信息,应该调整查询分析器中的设置,“选项”——“结果”
2、多表显示 select * from stu inner join grade on stu.number=grade.number for xml auto
select stu.number,name,course,grade from stu inner join grade on stu.number=grade.number for xml auto
嵌套次序发生改变(只是利用投影字段的名称次序) select course,grade,stu.number,name from stu inner join grade on stu.number=grade.number for xml auto
3、格式控制 select 1 as TAG, NULL as PARENT,stu.number as [stus!1!sid],stu.name as [stus!1!name] from stu for xml explicit 显示如: <stus sid="000001" name="黎明"/> <stus sid="000002" name="赵怡春"/> <stus sid="000003" name="张富平"/> <stus sid="000004" name="白丽"/> ...
说明: 1)1 as TAG, NULL as PARENT是不能省略的,表示当前定义的标签号和父节点,NULL表示没有 2)[stus!1!sid]:[元素名称!元素号!属性名称]
事实上,上述结果也可以使用其他方式得到: select number as sid, name from stu for xml auto
添加元素标识信息: 指定哪个元素是ID元素 select 1 as TAG, NULL as PARENT,stu.number as [stus!1!sid!id],stu.name as [stus!1!name] from stu for xml explicit,xmldata
指定生成元素形式而非属性形式的XML结果 select 1 as TAG, NULL as PARENT,stu.number as [stus!1!sid!id!element],stu.name as [stus!1!name!element] from stu for xml explicit,xmldata
指定元素值不自动进行转义字符转换,如XML换成element会自动转换 select 1 as TAG, NULL as PARENT,stu.number as [stus!1!sid!id!element],stu.name as [stus!1!name!XML] from stu for xml explicit
4、XML转换为关系表 DECLARE @hdoc int DECLARE @doc varchar(1000)
-- Source XML document§不能使用汉字 SET @doc =\' <root> <stu sid= "000001" name="LM" sex="1"> <grade cid="A03" grade="56"/> <grade cid="A02" grade="90"/> </stu> <stu sid= "000002" name="ZYC" sex="0"> <grade cid="A03" grade="60"/> <grade cid="B01" grade="61"/> </stu> </root> \'
--Create an internal representation of the XML document. EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc
SELECT * FROM OPENXML (@hdoc, \'/root/stu/grade\') WITH (cid varchar(6),grade int)
EXEC sp_xml_removedocument @hdoc
假如有个表结构和XML生成的关系结构相同,就可以更改上述语句实现插入记录: (SELECT * into stugrades FROM OPENXML (@hdoc, \'/root/stu/grade\') WITH (cid varchar(6),grade int) where 1=0 生成表结构) 上述语句也可以写为:SELECT * FROM OPENXML (@hdoc, \'/root/stu/grade\') WITH stugrades 插入记录为:insert into stugrades SELECT * FROM OPENXML (@hdoc, \'/root/stu/grade\') WITH stugrades
[此贴子已经被作者于2010-12-11 19:55:08编辑过]
|