检索导入到SQL Server多个XML

时间:2017-11-08 15:17:07

标签: sql-server xml sqlxml sql-server-2017

我有多个具有相同结构的XML文件,我已使用以下命令将它们导入 SQL Server 2017

DDL:

CREATE DATABASE xmlFiles
GO

USE xmlFiles
CREATE TABLE tblXMLFiles (IntCol int, XmlData xml);
GO

DML:

USE xmlFiles
INSERT INTO [dbo].[tblXMLFiles](XmlData) SELECT * FROM OPENROWSET(BULK 'C:\xmls\1.xml', SINGLE_BLOB) AS x;
INSERT INTO [dbo].[tblXMLFiles](XmlData) SELECT * FROM OPENROWSET(BULK 'C:\xmls\2.xml', SINGLE_BLOB) AS x;
…
INSERT INTO [dbo].[tblXMLFiles](XmlData) SELECT * FROM OPENROWSET(BULK 'C:\xmls\N.xml', SINGLE_BLOB) AS x;

现在我想查询数据:

USE xmlFiles
GO

DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)

SELECT @XML = XmLData FROM tblXMLFiles

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT Surname , GivenNames
FROM OPENXML(@hDoc, 'article/ref-list/ref/mixed-citation')
WITH 
(
    Surname [varchar](100) 'string-name/surname',
    GivenNames [varchar](100) 'string-name/given-names'
)

EXEC sp_xml_removedocument @hDoc
GO

查询正在运行,但问题是只有当数据源表中只有一行 - tblXMLFiles时才会返回数据。如果我添加多行,我会得到空的结果集。

重要的:
如果我向SELECT语句添加外SELECT @XML = XmLData…子句(TOP),那么情况就会发生变化,然后根据{{1}返回特定行号的查询数据}值。

问题:
如何在表格中只有一行但很多行的情况下检索数据?

1 个答案:

答案 0 :(得分:2)

FROM OPENXML与相应的SP准备和删除文档已过时,不应再使用。而是使用适当的methods the XML data type provides

如果没有XML的例子,很难提供解决方案,但我的魔法水晶球告诉我,它可能是这样的:

SELECT f.IntCol 
      ,mc.value('(string-name/surname)[1]','nvarchar(max)') AS Surname
      ,mc.value('(string-name/given-names)[1]','nvarchar(max)') AS GivenNames
FROM dbo.tblXMLFiles AS f
OUTER APPLY f.XmlData.nodes('article/ref-list/ref/mixed-citation') AS A(mc)