PIVOT Result Set WIP

 declare @sql nvarchar(max) = N'select top 10 * from dbo.TierReport where yy=''2017'' and mm=''01''';


select * from sys.dm_exec_describe_first_result_set(@sql,null,1)

exec sp_executesql @stmt=@sql


set nocount on;

declare 
  @sql nvarchar(max) = N'select top 10 * from dbo.TierReport where yy=''2017'' and mm=''01'''
, @temp_table_name sysname = N'#pivot_resultset';


select 'create table ' + @temp_table_name + '(' 
select '[' + [name] + '] ' + [system_type_name] + ',' from sys.dm_exec_describe_first_result_set(@sql,null,1)
select 'eof int'  
select ');'


select 'insert ' + @temp_table_name
select 'exec sp_executesql @stmt=@sql'

select 'select * from ' + @temp_table_name



Table has 0-N custom attributes.  Want to get 1-N custom attributes into an XML document.

CREATE PROCEDURE [dbo].[CAQH_PivotOfficeCustomAttributeData]
as
begin
set nocount on;

truncate table [dbo].[CAQH_OfficeCustomAttribute];

select
  EntityId,
 '<CustomAttribute Name=' + '''' + AttributeName + '''' 
  +  ' DataType=' + '''' + DataTypeCode + '''' 
  +  ' Value=' + '''' + AttributeValue + '''' + ' />' xmlPayload
into #RawOfficeCustomAttribute
from [Medimart].[ExportOfficeCustomAttributeData]

declare 
  @entityid int
, @xmlpayload varchar(max)
, @preventityid int = -1
, @customattribute varchar(max) = '';

declare xml_cursor cursor static for
select EntityId, xmlPayload from #RawOfficeCustomAttribute
order by EntityId;

open xml_cursor;
fetch next from xml_cursor into @entityid, @xmlpayload;

while @@fetch_status = 0
begin
if @entityid <> @preventityid
begin
if len(@customattribute) > 0
begin
set @customattribute += '</xml>'
insert [dbo].[CAQH_OfficeCustomAttribute] 
(EntityId, XmlPayload)
values
(@preventityid, @customattribute);
end
set @customattribute = '<xml>' + @xmlpayload;
set @preventityid = @entityid;
end
else
begin
set @customattribute += @xmlpayload;
end

fetch next from xml_cursor into @entityid, @xmlpayload;
end

if len(@customattribute) > 0
begin
set @customattribute += '</xml>'
insert [dbo].[CAQH_OfficeCustomAttribute] 
(EntityId, XmlPayload)
values
(@preventityid, @customattribute);
end

close xml_cursor;
deallocate xml_cursor;

end




Comments

Popular posts from this blog

Using sp_executesql with OPENQUERY

Executing Remote Queries Safely and Efficiently with sp_executesql