简体   繁体   English

SQL Server 2008-从OPENXML语句中选择多个行

[英]SQL Server 2008 - Selecting multiple rows from OPENXML statement

I have an XML file and I open that in SQL Server using OPENXML and then read the values in the XML file and insert them into the table. 我有一个XML文件,我使用OPENXML在SQL Server中打开它,然后读取XML文件中的值并将它们插入表中。 Assume that the XML structure is like this 假设XML结构是这样的

<Student>
   <name>XYZ</name>
   <id>123</id>
   <fathersname>XYS</fathersname>
   <fathersid>3489</fathersid>
</Student>".

Now I need to add this as two different rows and the DB should look like this 现在,我需要将其添加为两个不同的行,并且数据库应如下所示
Name ID Name ID
XYZ 123
XYS 3489
How can i read from this XML and insert as two different rows using a single OPENXML statement? 如何从此XML读取并使用单个OPENXML语句作为两个不同的行插入?

CREATE TABLE dbo.Person(ID int, [Name] varchar(50))

DECLARE @docHandle int

DECLARE @xmlDocument XML
SET @xmlDocument = N'<ROOT>
<Student>
  <name>XYZ</name>
  <id>123</id>
  <fathersname>XYS</fathersname>
  <fathersid>3489</fathersid>
</Student>
<Student>
  <name>ABC</name>
  <id>456</id>
  <fathersname>DEF</fathersname>
  <fathersid>7859</fathersid>
</Student>
</ROOT>'

EXEC sp_xml_preparedocument @docHandle OUTPUT, @xmlDocument

-- student's data first
INSERT INTO dbo.Person
SELECT * 
  FROM OPENXML(@docHandle, N'/ROOT/Student',2) 
    WITH (id int, name varchar(50))

-- now insert father's data
INSERT INTO dbo.Person
SELECT * 
  FROM OPENXML(@docHandle, N'/ROOT/Student',2) 
    WITH (fathersid int, fathersname varchar(50))


SELECT * FROM dbo.Person

EXEC sp_xml_removedocument @docHandle 
DROP TABLE dbo.Person

To open from a file: 要从文件打开:

declare @xmlDocument XML
SET @xmlDocument=(SELECT * FROM OPENROWSET(
   BULK 'c:\Temp\Student.xml',
   SINGLE_BLOB) AS x)

UPDATE: 更新:
Sorry, did not see that you are trying to split <father> into a different row, I have simply added one more INSERT for that. 抱歉,没有看到您尝试将<father>拆分为另一行,为此我仅添加了一个INSERT。 If you need more control over the loading process, you can always consider setting up an ETL job in SSIS. 如果需要对加载过程进行更多控制,则始终可以考虑在SSIS中设置ETL作业。

UPDATE 2 更新2
Well here is a creative way with one insert only, but two selects -- not sure about the performance at all. 好吧,这是一种只用一个插入物,但有两个选择的创造性方法-完全不确定性能。 Again, we are splitting one record into two rows. 同样,我们将一条记录分为两行。

INSERT INTO dbo.Person
    SELECT 
        x.e.value('id[1]', 'int') AS "id"
        ,x.e.value('name[1]', 'varchar(10)') AS "Name"  
    FROM @xmlDocument.nodes('/ROOT/Student') AS x(e)
    UNION
    SELECT 
        x.e.value('fathersid[1]', 'int') AS "id"
        ,x.e.value('fathersname[1]', 'varchar(10)') AS "Name"
    FROM @xmlDocument.nodes('/ROOT/Student') AS x(e);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM