Friday, 16 August 2013

SQL to XML & XML to SQL


--------convert sql to xml------------------
SET @XML=(SELECT * FROM t1 FOR XML AUTO,ELEMENTS,ROOT('MAIN'))

SELECT @XML

------------------CONVERT XML to SQL TABLE---------------

ALTER PROC usp_xml(@str XML)
AS
BEGIN
SELECT X.Y.value('id[1]','int')AS ID,X.Y.value('name[1]','varchar(50)')AS NAME FROM @str.nodes('/MAIN/t1') X(Y)
END
DECLARE @EXML XML='<MAIN>
  <t1>
    <id>1</id>
    <name>suresh</name>
  </t1>
  <t1>
    <id>2</id>
    <name>naresh</name>
  </t1>
  <t1>
    <id>4</id>
    <name>naresh</name>
  </t1>
 
</MAIN>'
EXEC usp_xml @EXML

**Note: t1-table name
             id-column id
            name-column name

No comments:

Post a Comment

EMP, DEPT Sample script

/****** Object:  Table [dbo].[DEPT]    Script Date: 19-05-2016 06:58:37 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET A...