IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[xml2table]') AND type = 'P')
DROP PROCEDURE [dbo].[xml2table]
GO
create procedure [dbo].[xml2table](
@xml xml,
@dsname varchar(1000),
@flds varchar(4000),
@totbname varchar(1000) = default 
)
as 
begin
declare @i int 
declare @s1 varchar(100) 
declare @s2 varchar(100) 
if (CHARINDEX('/',@dsname)<=0) set @dsname='//'+@dsname
set @totbname = ISNULL(@totbname,'') 
if (@totbname='') 
begin
set @totbname = @dsname
set @i = CHARINDEX('/',@totbname)  
while (@i>0) 
begin
set @totbname = SUBSTRING(@totbname,@i+1,1000)
set @i = CHARINDEX('/',@totbname)  
end 
set @totbname = '#'+@totbname 
end 
declare @tbex int 
declare @sql nvarchar(4000) 
if (CHARINDEX('#',@totbname)>0) 
begin
exec drop_temp_table @totbname 
end else
begin
exec mps_sys_checktable @totbname,@tbex output  
if (@tbex=0)
begin
set @sql =' drop table '+@totbname 
execute(@sql) 
end 
end 
set @sql='' 

declare @index varchar(1000) 
set @index = '' 
while (@flds>'') 
begin
set @i = CHARINDEX('|',@flds) 
if (@i>0) 
begin
set @s1 = SUBSTRING(@flds,1,@i-1) 
set @flds = SUBSTRING(@flds,@i+1,4000) 
end else 
begin
set @s1 = @flds 
set @flds = ''
end 
set @i = CHARINDEX('=',@s1) 
if (@i>0) 
begin
set @s2 = SUBSTRING(@s1,@i+1,100) 
set @s1 = SUBSTRING(@s1,1,@i-1) 
end else 
begin
set @s2 = '' 
set @s1 = @s1 
end 
if (@s2='') set @s2 = 'nvarchar(200)' 
if (@sql>'')  set @sql = @sql +' , ' 
if (CHARINDEX('*',@s1)>0) 
begin
set @s1 = REPLACE(@s1,'*','') 
if (@index>'') set @index = @index +',' 
set @index = @index +@s1 
end 
set @sql=@sql + 'c.value('''+@s1+'[1]'','''+@s2+''') as '+@s1 
end 

declare @istemp int 
set @istemp = 1 
if (charindex('##',@totbname)<=0 and charindex('#',@totbname)=1) set @istemp = 0 
set @sql = 'select '+@sql+' into '+@totbname+' from @xml.nodes('''+@dsname+''') as T(c) ' 
if (@istemp=0) 
set @sql = @sql+char(13)+char(10)+'select * from '+@totbname+' ' 
exec sp_executesql @sql, N'@xml xml', @xml 

if (@index>'') 
begin
set @sql = 'CREATE INDEX '+@totbname+'_index_'+@totbname+
' ON '+@totbname+'('+@index+') '
execute(@sql) 
end 
end