原文地址: http://www.microsoft.com/china/msdn/library/data/sqlserver/XMLDML.mspx?mfr=true
(7)将节点插入类型化的xml列中
在下面的示例中,首先创建了一个架构集合,并建立了一个使用该架构集合的表。在使用Transact-SQL INSERT语句向表中插入一个符合架构约束的XML后,再使用XML DML insert向该XML中插入一个item节点。
-- 创建XML架构集合
CREATE XML SCHEMA COLLECTION MySchemas
AS
N'<?xml version = "1.0"?>
<xsd:schema targetNamespace="http://schemas.mybook.com/customerschemas"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="customer">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="item">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="customername" type="xsd:string"/>
<xsd:element name="address" type="xsd:string"/>
<xsd:element name="phone" type="xsd:string"/>
<xsd:element name="contact" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="ID" type="xsd:int"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>';
GO
-- 创建包含xml数据类型列的表
CREATE TABLE MyCustomer
(CustomerID int IDENTITY PRIMARY KEY,
CustomerItem xml(MySchemas));
GO
-- 向表中插入XML,该XML应当符合http://schemas.mybook.com/customerschemas命名空间架构的定义
INSERT INTO MyCustomer
VALUES
(N'<C:customer xmlns:C="http://schemas.mybook.com/customerschemas">
<item ID="1">
<customername>北方书城</customername>
<address>北京市海淀区知春路22号</address>
<phone>2222222</phone>
<contact>刘先生</contact>
</item>
</C:customer>');
-- 使用XML DML insert插入另一个item节点到XML中
UPDATE MyCustomer
SET CustomerItem.modify('
declare namespace CS="http://schemas.mybook.com/customerschemas";
insert (<item ID="2">
<customername>东图大厦</customername>
<address>长春市朝阳大街99号</address>
<phone>1111111</phone>
<contact>孙小姐</contact>
</item>)
into (/CS:customer)[1] ')
WHERE CustomerID=1;
SELECT CustomerItem
FROM Mycustomer;
GO
执行上面的SELECT查询后,可以看到CustomerItem中的XML内容,如下所示:
<C:customer xmlns:C="http://schemas.mybook.com/customerschemas">
<item ID="1">
<customername>北方书城</customername>
<address>北京市海淀区知春路22号</address>
<phone>2222222</phone>
<contact>刘先生</contact>
</item>
<item ID="2">
<customername>东图大厦</customername>
<address>长春市朝阳大街99号</address>
<phone>1111111</phone>
<contact>孙小姐</contact>
</item>
</C:customer>