实验四 管理XML数据
一、目标
完成这个实验后,你将能够: 1、使用XML结构 2、检索XML数据 二、实验内容
实验开始前,请执行脚本instnwnd.sql,安装Northwind数据库。本实验均在Northwind数据库中完成。 三、实验报告内容
练习1:使用XML结构
1、创建一个含有XML类型字段的数据表。
以示例数据库Northwind为例,在该数据库中创建一个名为xml_Categories的数据表,该数据表中包含两个字段,如下表所示。 字段名 类 型 CategoryID Int,标识,且为主键 CategoryInfo XML 代码: CREATE TABLE xml_Categories (
CategoryID INT IDENTITY PRIMARY KEY, CategoryInfo XML );
2、向该数据表输入一条记录,CategoryInfo字段值如下:
INSERT INTO xml_Categories(CategoryInfo)
VALUES('
SELECT * FROM xml_Categories 结果:
4、创建XML数据类型变量,定义XML变量@CategoryInfo,将其值设置为
Sweet and savory sauces, relishes, spreads, and seasonings
代码:
DECLARE @CategoryInfo XML
SET @CategoryInfo='
Sweet and savory sauces, relishes, spreads, and seasonings '
SELECT @CategoryInfo 结果:
Sweet and savory sauces, relishes, spreads, and seasonings
5、将@CategoryInfo值插入xml_Categories表中。 代码:
DECLARE @CategoryInfo XML
SET @CategoryInfo='
Sweet and savory sauces, relishes, spreads, and seasonings '
INSERT xml_Categories(CategoryInfo)
VALUES(@CategoryInfo)
SELECT * FROM xml_Categories 结果:
练习2:创建架构集合
1、在数据库Northwind中创建一个名为testXMLSchema的XML架构集合。要求如下:
CREATE XML SCHEMA COLLECTION testXMLSchema AS
'
2、创建一个名为xsd_Categories的数据表,包含一个Categories字段,为XML类型,并将架构集合testXMLSchema与其关联。 代码:
CREATE TABLE xsd_Categories (
Categories XML(testXMLSchema)
)
3、向数据表xsc_Categories中插入一条记录,值为
INSERT xsd_Categories VALUES('
Select * from xsd_Categories 结果:
4、将上面的Transact SQL脚本稍作改动,将
结果为:消息6926,级别16,状态1,第1 行
XML 验证: 简单类型值'abcd' 无效。位置:
/*:CategoryInfo[1]/*:CategoryId[1]
原因是 testXMLSchema中定义的CategoryId的类型是integer
练习3:检索XML数据
1、使用FOR XML RAW模式,从Products表中输出前5条记录,结果如下。
SELCT TOP 5 ProducTID,PboductName,Supp,ierID,CAtegoryID frgm Products
ORDER BY ProductID FOR XML RAW
2、使用FOR XML RAW模式,从Products表中输出前5条记录,结果如下。
SELECT TOP 5 ProductID,ProductName,SupplierID,CategoryID from Products
ORDER BY ProductID
FOR XML RAW('Product'),ELEMENTS
3、使用FOR XML AUTO模式,从Categories和Products表中输出CategoryID为1或2的记录,包括每种类别的编号、名称、描述信息以及该种类别的产品信息,结果如下。