在XML文档插入SQL Server2000数据库(1) (http://blog.csdn.net/LoveLion/archive/2006/09/18/1237263.aspx
)中我讲了一下怎么将XML文档插入SQL server 2000数据库,但是有一个问题,怎么将一个现存的xml文档插入数据库,不把xml文档当成字符串来处理,而把它当作一个外部文件读入之后再进行处理,通过参考相关资料,可以通过下面的方法来进行操作:(假设电脑C盘下有一个名为product.xml的xml文件,其根节点/子节点是'/productdata/PRODUCTS'),该文件代码如下:
<?xml version="1.0" encoding="gb2312"?>
<productdata>
<PRODUCTS PRODUCTID="P030" PRODUCTNAME="BARBIE DOLL" DESCRIPTION="THIS IS A TOY FOR GIRLS" CATEGORY="TOY" PRICE="120" QOH="10" />
<PRODUCTS PRODUCTID="P031" PRODUCTNAME="MINI RACE CAR" DESCRIPTION="THIS IS A TOY FOR BOYS" CATEGORY="TOY" PRICE="130" QOH="12" />
<PRODUCTS PRODUCTID="P032" PRODUCTNAME="BABYS RATTLE" DESCRIPTION="THIS IS A TOY FOR BABIES" CATEGORY="TOY" PRICE="80" QOH="24" />
</productdata>
通过以下程序在查询分析器中执行可以将以上数据插入表PRODUCTS:
DECLARE @FileName VARCHAR(255)
DECLARE @ExecCmd VARCHAR(255)
DECLARE @FileContents VARCHAR(8000)
DECLARE @idoc int
DECLARE @y INT
DECLARE @x INT
CREATE TABLE #tempXML(PK INT NOT NULL IDENTITY(1,1), ThisLine VARCHAR(255))
SET @FileName = 'C:/product.xml'
SET @ExecCmd = 'type ' + @FileName
SET @FileContents =''
INSERT INTO #tempXML EXEC master.dbo.xp_cmdshell @ExecCmd
SELECT @y = count(*) from #tempXML
SET @x = 0
WHILE @x <> @y
BEGIN
SET @x = @x + 1
SELECT @FileContents = @FileContents + ThisLine from #tempXML WHERE PK = @x
END
SELECT @FileContents as FileContents
DROP TABLE #tempXML
EXEC sp_xml_preparedocument @idoc OUTPUT, @FileContents
SELECT *
FROM OPENXML (@idoc, '/productdata/PRODUCTS', 1)
WITH (PRODUCTID char(4),
PRODUCTNAME VARCHAR(50),
DESCRIPTION varchar(100),
CATEGORY varchar(10)
)
INSERT PRODUCTS
SELECT *
FROM OPENXML(@idoc, '/productdata/PRODUCTS')
WITH PRODUCTS
EXEC sp_xml_removedocument @idoc
select * from products
该程序将XML文档首先以行为单位循环读入一个字符串变量@FileContents ,并创建一个临时表#tempXML来存储该xml文档生成的字符串,待文件处理完毕后删除该临时表,把@FileContents 带入http://blog.csdn.net/LoveLion/archive/2006/09/18/1237263.aspx 所述方法中进行处理.从而实现对外部xml文档的插入.