Thursday 20 April 2017

Dynamically Transposing values into multiple columns if it contains with Delimiter :

I have a table named is #temp with following values
create table #Temp(ID int,barcode_type varchar(50))
insert into #Temp values(12345,'AAAA,BBBB,CCCC,DDDD,EEEE,FFFF,GGGG')
insert into #Temp values(12346,'GGGG,FFFF,EEEE,DDDD,CCCC,BBBB,AAAA')
insert into #Temp values(12347,'MMMM,NNNN,OOOO,PPPP,QQQQ,RRRR,SSSS')
select * from #Temp
Step1: will create multiple columns after counting the maximum words from #temp 
table (Barcode_Type column) into a separate table named #len_of_words.
Step2: Execute the following code and let see the results what will come.

Select ID,barcode_type,len(barcode_type) - len(replace(barcode_type, ',', '')) + 1 No_of_Count
into #len_of_words from #Temp
declare @c as int=1
declare @i as int
select @i=max(No_of_Count) from #len_of_words
while (@c<=@i)
begin
EXEC ('ALTER TABLE #len_of_words ADD barcode_type'+@c+' VARCHAR(100);')
exec('update t1 set barcode_type'+@c+'= NewXML.value(''/Product[1]/Attribute['+@c+']'',''varchar(50)'')
FROM #len_of_words t1
CROSS APPLY (SELECT XMLEncoded=(SELECT barcode_type AS [*] FROM #Temp t2 WHERE t1.ID = t2.ID FOR XML PATH(''''))) EncodeXML
CROSS APPLY (SELECT NewXML=CAST(''<Product><Attribute>''+REPLACE(XMLEncoded,'','',''</Attribute><Attribute>'')+''</Attribute></Product>'' AS XML)) CastXML')
set @c=@c+1
end

select * from #len_of_words


No comments:

Post a Comment