how to import data from this XML file to Table

  • HI

    CREATE TABLE Customer (

    CustomerId INT PRIMARY KEY,

    CompanyName NVARCHAR(20),

    City NVARCHAR(20))

    and values are in XML like:

    ROOT>

    <Customers>

    <CustomerId>1</CustomerId>

    <CompanyName>Name1</CompanyName>

    <City>City1</City>

    </Customers>

    <Customers>

    <CustomerId>2</CustomerId>

    <CompanyName>Name2</CompanyName>

    <City>City2</City>

    </Customers>

    <Customers>

    <CustomerId>3</CustomerId>

    <CompanyName>Name3</CompanyName>

    <City>City3</City>

    </Customers>

    </ROOT>

    how to import data from this XML file to Customer Table with Query only

    Thanks
    Parthi

  • Hi

    To load XML from file into a variable use OPENROWSET:

    DECLARE @blob XML;

    SELECT @blob = BulkColumn

    FROM OPENROWSET(

    BULK N'C:\Temp\test.xml'

    ,SINGLE_BLOB

    ) t

    Parse XML content try XQuery:

    DECLARE @Customer TABLE (

    CustomerId INT PRIMARY KEY

    ,CompanyName NVARCHAR(20)

    ,City NVARCHAR(20)

    );

    DECLARE @xml XML = '<ROOT>

    <Customers>

    <CustomerId>1</CustomerId>

    <CompanyName>Name1</CompanyName>

    <City>City1</City>

    </Customers>

    <Customers>

    <CustomerId>2</CustomerId>

    <CompanyName>Name2</CompanyName>

    <City>City2</City>

    </Customers>

    <Customers>

    <CustomerId>3</CustomerId>

    <CompanyName>Name3</CompanyName>

    <City>City3</City>

    </Customers>

    </ROOT>'

    INSERT INTO @Customer

    SELECT

    T.C.value('(CustomerId)[1]', 'int')

    ,T.C.value('(CompanyName)[1]', 'nvarchar(20)')

    ,T.C.value('(City)[1]', 'nvarchar(20)')

    FROM @xml.nodes('ROOT/Customers') T(C)

    Greets

    Flo

  • hi

    Nice one it worked out.Say for eg: take this as input of the below query's output it is in XML then how to load this in to my New table which is having ProductID, Name, Color

    SELECT ProductID, Name, Color

    FROM Production.Product

    FOR XML RAW, root('my');

    GO

    Thanks
    Parthi

  • What about having a look into BOL for XML methods like "nodes" and "value"? 😎

    Tip: FOR XML doesn't work in your case, it works to create XML, not to parse.

    Greets

    Flo

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply