clear markdown compare help best fiddles feedback dbanow.uk a leap of faith?
clear markdown donate comments/suggestions/bugs a leap of faith? bible365 diddy dollings
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0. 1305693 fiddles created (20204 in the last week).

CREATE TABLE Import_Table ( import_id INT IDENTITY, Test1 decimal(5,2), Test2 decimal(5,2), Test3 decimal(7,3) ) CREATE TABLE Fields ( FieldName VARCHAR(255) )
 hidden batch(es)


INSERT INTO Import_Table VALUES (323,2.3,4.5) INSERT INTO Fields VALUES ('Test1'), ('Test2'), ('Test3')
4 rows affected
 hidden batch(es)


SELECT Import_id, p.Field, p.Value FROM ( SELECT Import_id, CAST(Test1 AS VARCHAR) AS Test1, CAST(Test2 AS VARCHAR) AS Test2, CAST(Test3 AS VARCHAR) AS Test3 FROM Import_Table ) src UNPIVOT ( Value FOR Field IN (Test1, Test2, Test3) ) p
Import_id Field Value
1 Test1 323.00
1 Test2 2.30
1 Test3 4.500
 hidden batch(es)


DECLARE @Sql NVARCHAR(MAX) SET @Sql = ' SELECT Import_id, p.Field, p.Value FROM ( SELECT Import_id, ' SELECT @Sql = @Sql + STRING_AGG('CAST(' + FieldName + ' AS VARCHAR) AS ' + FieldName, ', ') FROM Fields SET @Sql = @Sql + ' FROM Import_Table ) src UNPIVOT ( Value FOR Field IN (' SELECT @Sql = @Sql + STRING_AGG(FieldName, ', ') FROM Fields SET @Sql = @Sql + ') ) p' EXEC sp_executesql @Sql
Import_id Field Value
1 Test1 323.00
1 Test2 2.30
1 Test3 4.500
 hidden batch(es)