Home > Net >  Create new tables based on existing tables with different column names
Create new tables based on existing tables with different column names

Time:01-03

I have two tables. One is the raw table and another one is the table that I need to reference from. I am not sure how to join this two tables because the structure is different. I am trying to create two new tables based on the reference table. Below is the sample data and expected output:

#Raw table

Sbjnum B_01 B_02 C_01 C_02
172009172 100 120 200 240
172009173 200 140 220 250
172009174 300 150 240 260

#Specnorm

tablename fieldname destfieldname sequence
Screener B_01 Area1 1
Screener B_02 Area2 2
Product C_01 ProductID1 3
Product C_02 ProductID2 4

Expected output

#Screener table

Sbjnum Area1 Area2
172009172 100 120
172009173 200 140
172009174 300 150

#Harvest table

Sbjnum ProductID1 ProductID2
172009172 200 240
172009173 220 250
172009174 240 260

CodePudding user response:

Try to build on this:

DROP TABLE IF EXISTS #Specnorm;

CREATE TABLE #Specnorm
(
    [tablename] SYSNAME
   ,[fieldname] SYSNAME
   ,[destfieldname] SYSNAME
   ,[sequence] BIGINT
);

INSERT INTO #Specnorm ([tablename], [fieldname], [destfieldname], [sequence])
VALUES ('Screener' ,'B_01', 'Area1' ,   1)
      ,('Screener' ,'B_02', 'Area2' ,   2)
      ,('Product'  ,'C_01', 'ProductID1',   3)
      ,('Product'  ,'C_02', 'ProductID2',   4);

DECLARE @source_data_table_name SYSNAME = '#Raw';
DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

SELECT @DynamicTSQLStatement = STRING_AGG(CAST([table_definiton] AS NVARCHAR(MAX)), ';')
FROM
(
    SELECT 'SELECT '   STRING_AGG(CAST(QUOTENAME([fieldname])   ' AS '   QUOTENAME([destfieldname]) AS NVARCHAR(MAX)), ', ') WITHIN GROUP (ORDER BY [sequence])     ' INTO '   MAX([tablename])   ' FROM '   @source_data_table_name    
    FROM #Specnorm
    GROUP BY [tablename]
) DS ([table_definiton])

EXEC sp_executesql @DynamicTSQLStatement;
  • Related