Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert xml data into table in sql server 2005

my table structure is

CREATE TABLE [dbo].[Emp](
    [ID] [int] NOT NULL,
    [EmpName] [varchar](50)  NOT NULL,
    [Sal] [int] NULL,
) 

in this emp table i want to insert data from a xml string

the xml is

<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Emp>
<ID>3</ID><EmpName>Dibyendu</EmpName><Sal>3500</Sal></Emp></Record>

suppose this xml is stored in a variable in my store procedure and i just want to insert this xml in such a way that in EMP table as a result ID data will insert into ID column, EmpName data will insert into EmpName column and Sal data will insert into Sal column.

so please tell me how to write the code in store procedure.

thanks

like image 977
Thomas Avatar asked Jan 21 '11 12:01

Thomas


People also ask

How insert bulk data in SQL Server using XML?

When you bulk import XML data from a file that contains an encoding declaration that you want to apply, specify the SINGLE_BLOB option in the OPENROWSET(BULK...) clause. The SINGLE_BLOB option ensures that the XML parser in SQL Server imports the data according to the encoding scheme specified in the XML declaration.

How use XML data in SQL Server?

To create a SQL table using XML elements, all you have to do is to change the mode value of the OPENXML function to 2 and change the name of the attributes to the name of the element you want to retrieve.

Can we store XML in SQL?

In SQL Server, you usually store XML data in a column configured with the xml data type. The data type supports several methods that let you query and modify individual elements, attributes, and their values directly within the XML instance, rather than having to work with that instance as a whole.


1 Answers

Assuming XML sample as above:

<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Emp>
        <ID>3</ID>
        <EmpName>Dibyendu</EmpName>
        <Sal>3500</Sal>
    </Emp>
</Record>

Assuming the following table:

CREATE TABLE Employee
(
    [ID] [int] NOT NULL,  
    [EmpName] varchar(max) NOT NULL,   
    [Sal] [int] NULL
)

The following stored procedure, that uses xpaths, should do the trick

CREATE PROCEDURE AddEmployee
    @empXml xml
AS

INSERT INTO Employee
(
    ID,
    EmpName,
    Sal
)
VALUES
(
    @empXml.value('(/Record/Emp/ID)[1]', 'int'),
    @empXml.value('(/Record/Emp/EmpName)[1]', 'varchar(max)'),
    @empXml.value('(/Record/Emp/Sal)[1]', 'int')
)

Which you can then execute with:

exec AddEmployee '<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Emp><ID>3</ID><EmpName>Dibyendu</EmpName><Sal>3500</Sal></Emp></Record>' 

You will need to do a little refactoring if the Record XML could potentially include multiple 'Emp' elements.

like image 189
MrEyes Avatar answered Jan 01 '23 10:01

MrEyes