Saturday, June 19, 2010

Get table from XML

I was sterling to convert the xml and get the table from the XML. But I did some work around and I am successfully done that here I am writing the stored procedure from the we can get the table from the XML that may help you any time..

Create PROCEDURE [dbo].[GetTableFormXML]
-- XML where from we need table

@xml xml
AS
BEGIN

SET NOCOUNT ON;
declare @OutputTable TABLE
(
nodeName varchar(max),
nodeValue varchar(max)
)
-- Insert statements for procedure here
DECLARE @xmldoc int,@tbl sysname,@sql nvarchar(4000),
@sql1 nvarchar(4000),@intCount int,@intFlag INT,
@Valuetext varchar(max)

set @Valuetext =''

declare @tempTable AS table( nodeName varchar(max))
declare @strValue as Table(value varchar(max))

EXEC sp_xml_preparedocument @xmldoc OUTPUT, @xml -- load the xml data
insert @tempTable
--Select all the node values
SELECT nodeName = localname FROM OPENXML (@xmldoc, '//.') where parentid is not null and nodetype = 1 --Select all the node accept root node and the attribute
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT nodeName FROM @tempTable
OPEN tblcur
SET @intFlag = 1
WHILE (@intFlag <= (SELECT COUNT(*) FROM @tempTable)) BEGIN FETCH tblcur INTO @tbl IF @@fetch_status <> 0
BREAK
SELECT @sql = N'SELECT * FROM OPENXML (@xmldoc, ''//'+ @tbl +''') WITH (Col1 varchar(200) ''text()'')'

set @intFlag = @intFlag + 1

insert @strValue EXEC sp_executesql @sql,N'@xmldoc int',@xmldoc -- Select the node value


INSERT INTO @OutputTable (nodeName, nodeValue)
SELECT @tbl, value
FROM @strValue

delete @strValue -- Clear the data again

END
EXEC sp_xml_removedocument @xmldoc
select * from @OutputTable
END

No comments: