Вопрос

Hi I am trying to insert data into an SQL Server Database using an XML file which has some data as follows.I was able to do the attribute mapping in OPENXML.If i try to pass the XML as elements instead of attributes i get an error regarding the null insertion.

Following is my XML FILE (containg attributes)

<NewDataSet>
  <SampleDataTable id="20" Name="as" Address="aaa" Email="aa" Mobile="123" />
</NewDataSet>

I am successful using the above format.If i use the below format i face errors

<Customer>
  <Id>20</Id>
  <Name>Cn</Name>
  <Address>Pa</Address>
  <Email>bnso@gmail.com</Email>
  <Mobile>12345513213</Mobile>
</Customer>

This is my openXML in SQL

 insert into @tempTable
    select * from openxml (@xmlHandle,'ROOT/Customer/',1)
    with (Cust_id int '@id',
          Customer_Name varchar(30) '@Name',
          Address varchar(30) '@Address',
          Email_id varchar(30) '@Email',
          Mobile_no bigint '@Mobile'
          )

    Insert into Test.dbo.tblCustomers (Cust_id,Customer_Name,Address,Email,Mobile_No) (select * from @tempTable)

please help

Это было полезно?

Решение

It's because you're trying to fetch data as attributes, but int your xml data is inside elements. Try this:

insert into @tempTable
select *
from openxml (@xmlHandle,'ROOT/Customer/',1)
with (Cust_id int '@id',
      Customer_Name varchar(30) 'Name[1]',
      Address varchar(30) 'Address[1]',
      Email_id varchar(30) 'Email[1]',
      Mobile_no bigint 'Mobile[1]'
      )

Or you can do this without openxml:

select
    t.c.value('Name[1]', 'varchar(30)') as Name,
    t.c.value('Address[1]', 'varchar(30)') as Address,
    t.c.value('Email[1]', 'varchar(30)') as Email,
    t.c.value('Mobile[1]', 'bigint') as Mobile
from @Data.nodes('Customer') as t(c)

sql fiddle demo

Другие советы

The problem is "element value" vs "element attribute".

This page has good examples of both:

http://technet.microsoft.com/en-us/library/ms187897%28v=sql.90%29.aspx

<Customer>   
   <CustomerID>LILAS</CustomerID>
   <ContactName>Carlos Gonzlez</ContactName>
   <Order OrderID="10283" CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
      <OrderDetail ProductID="72" Quantity="3"/>
   </Order>
</Customer>
</ROOT>'

-- Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @XmlDocumentHandle OUTPUT, @XmlDocument

-- Execute a SELECT statement using OPENXML rowset provider.
SELECT    *
FROM      OPENXML (@XmlDocumentHandle, '/ROOT/Customer',2)
           WITH (CustomerID  varchar(10),
                 ContactName varchar(20))
EXEC sp_xml_removedocument @XmlDocumentHandle
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top