如何对SQL Server中的XML数据进行insert、update、delete .
	    SQL Server 2005/2008增加了对XML数据的支持,同时也新增了几种操作XML的方法,本文主要以SQL Server 2008为例介绍如何对XML数据进行insert、update、delete。
	      SQL Server中新增加了XML.Modify()方法,分别为xml.modify(insert),xml.modify(delete),xml.modify(replace)对应XML的插入,删除和修改操作。
	      本文以下面XML为例,对三种DML进行说明:
	 
	declare @XMLVar xml = ' 
	<catalog> 
	 <book category="ITPro"> 
	 <title>Windows Step By Step</title> 
	 <author>Bill Zack</author> 
	 <price>49.99</price> 
	 </book> 
	 <book category="Developer"> 
	 <title>Developing ADO .NET</title> 
	 <author>Andrew Brust</author> 
	 <price>39.93</price> 
	 </book> 
	 <book category="ITPro"> 
	 <title>Windows Cluster Server</title> 
	 <author>Stephen Forte</author> 
	 <price>59.99</price> 
	 </book> 
	</catalog> 
	'
	1.XML.Modify(Insert)语句介绍
	A.利用as first,at last,before,after四个参数将元素插入指定的位置
	 
	 
	set @XMLVar.modify( 
	 'insert <first name="at first" /> as first into (/catalog[1]/book[1])') 
	set @XMLVar.modify( 
	 'insert <last name="at last"/> as last into (/catalog[1]/book[1])') 
	set @XMLVar.modify( 
	 'insert <before name="before"/> before (/catalog[1]/book[1]/author[1])') 
	set @XMLVar.modify( 
	 'insert <after name="after"/> after (/catalog[1]/book[1]/author[1])') 
	SELECT @XMLVar.query('/catalog[1]/book[1]'); 
	  
	结果集为:
	 1: <book category="ITPro">
	 2: <first name="at first" />
	 3: <title>Windows Step By Step</title>
	 4: <before name="before" />
	 5: <author>Bill Zack</author>
	 6: <after name="after" />
	 7: <price>49.99</price>
	 8: <last name="at last" />
	 9: </book>
	 
	B.将多个元素插入文档中
	 
	--方法一:利用变量进行插入 
	DECLARE @newFeatures xml; 
	SET @newFeatures = N'; 
	<first>one element</first> 
	<second>second element</second>' 
	SET @XMLVar.modify(' ) 
	insert sql:variable("@newFeatures") 
	into (/catalog[1]/book[1])' 
	--方法二:直接插入 
	set @XMLVar.modify(') 
	insert (<first>one element</first>,<second>second element</second>) 
	into (/catalog[1]/book[1]/author[1])' 
	SELECT @XMLVar.query('/catalog[1]/book[1]'); 
	 
	结果集为:
	 
	 1: <book category="ITPro">
	 2:  <title>Windows Step By Step</title>
	 3:  <author>Bill Zack
	 4:  <first>one element</first>
	 5:  <second>second element</second>
	 6:  </author>
	 7:  <price>49.99</price>
	 8:  <first>one element</first>
	 9:  <second>second element</second>
	 10: </book>
	 
	 
	C.将属性插入文档中
	 
	--使用变量插入 
	
相关新闻>>
- 发表评论
- 
				
- 最新评论 进入详细评论页>>




