We want to replicate rows and populate product code from mapping table.
My sample table structure is as below.
We have #tb_RawData table in which we received from another team.
We have #tb_productmapping mapping table in which we has product type and product code.
To populate [Product Type] in final Output we want to match the column header of the #tb_RawData with the #tb_productmapping (column product)
eg. We match the column header [Elect Prd] of #tb_RawData with the [Product[ column of #tb_productmapping and get the [Product Type] as 'Electronic'
We want to replicate all rows from #tb_RawData and populate product code in our #tb_final table.
Also I have attached the screen shot of RawData, Mapping Table, Final Output.
I am thinking of writing loop for this but we have around 10000 rows and 50 columns in raw data table
Is there any other better way to solve this problem
---------------SQL Scripts
/* RAW DATA */
IF OBJECT 1D ("tempdb..#tb RawData') IS NOT NULL DROP TABLE #tb_RawData
CREATE TABLE #tb_RawData
([Customer] VARCHAR (255), [Books prd] TINYINT, [Elect Prd] TINYINT, [Food Prd] TINYINT)
INSERT INTO #tb_RawData values (1,11,21,0)
INSERT INTO #tb_RawData values (2,0,0,31)
--select * from #tb_RawData
/* Mapping Table */
IF OBJECT ID('tempdb..#tb productmapping') IS NOT NULL DROP TABLE #tb_productmapping
create table #tb_productmapping ( product varchar (255), producttype varchar (255) )
insert into #tb_productmapping values ('Books prd', 'Books')
insert into #tb_productmapping values ('Elect Prd','Electronic')
insert into #tb_productmapping values ('Food Prd','Food')
--select * from #tb_productmapping
/* Final output */
IF OBJECT ID('tempdb..#tb_final') IS NOT NULL DROP TABLE #tb_final
create table #tb_final (Customer varchar (255), [Product Type] varchar (255), [Books prd] TINYINT, [Elect Prd] TINYINT, [Food Prd] TINYINT)
insert into #tb_final values (1,'Books',11,0,0)
insert into #tb_final values (1,'Electronic',0,21,0)
insert into #tb_final values (1,'Food',0,0,0)
insert into #tb_final values (2, 'Books',0,0,0)
insert into #tb_final values (2,'Electronic',0,0,0)
insert into #tb_final values (2, 'Food',0,0,31)
--select * from #tb_final