我正在尝试将 XML 文件导入SQL Server中的表。
这是我写的代码:
import
我最终在表格中得到了空值..
我需要做哪些修改?
以下是原始XML文件:
Declare @x xml
Select @x = p
from OpenRowSet(BULK 'C:\Users\sivat\OneDrive\Projects\SQL Server Projects\Books.xml',SINGLE_BLOB) as BOOKS(p)
Declare @hdoc int
exec sp_xml_preparedocument @hdoc output,@x
IF OBJECT_ID('BOOKS') IS NOT NULL
DROP Table BOOKS
select *
into BOOKS
from openxml(@hdoc,'/catalog/book',2)
with
( Author nvarchar(150),
Title nvarchar(150),
Genre nvarchar(150),
Price float,
Publish_Date Date,
Description nvarchar(200))
exec sp_xml_removedocument @hdoc
select * from BOOKS
答案 0 :(得分:1)
我更喜欢使用原生的内置XQuery方法,而不是使用笨重,内存泄漏的OPENXML
内容......
试试这段代码:
DECLARE @x XML
SELECT @x = p FROM OpenRowSet(BULK 'C:\Users\sivat\OneDrive\Projects\SQL Server Projects\Books.xml',SINGLE_BLOB) as BOOKS(p)
SELECT
Author = xc.value('(author)[1]', 'nvarchar(150)'),
Title = xc.value('(title)[1]', 'nvarchar(150)'),
Genre = xc.value('(genre)[1]', 'nvarchar(150)'),
Price = xc.value('(price)[1]', 'decimal(15,2)'),
Publish_Date = xc.value('(publish_date)[1]', 'date'),
Description = xc.value('(genre)[1]', 'nvarchar(200)')
FROM
@x.nodes('/catalog/book') AS XT(XC)
当然,只有显示值 - 但您可以轻松地将最终SELECT
替换为:
INSERT INTO dbo.Books(Author, Title, Genre, Price, Publish_Date, Description)
SELECT
Author = xc.value('(author)[1]', 'nvarchar(150)'),
Title = xc.value('(title)[1]', 'nvarchar(150)'),
Genre = xc.value('(genre)[1]', 'nvarchar(150)'),
Price = xc.value('(price)[1]', 'decimal(15,2)'),
Publish_Date = xc.value('(publish_date)[1]', 'date'),
Description = xc.value('(genre)[1]', 'nvarchar(200)')
FROM
@x.nodes('/catalog/book') AS XT(XC)
并将数据插入表dbo.Books
(在运行此语句之前必须存在)。
另请注意:我从Price
更改了float
的数据类型(众所周知,这很容易受到舍入错误的影响)并改为选择decimal(15,2)
(没有这些舍入错误)