asked on
CREATE TABLE
#TempTable (
CountryCode nvarchar(2),
CountryName nvarchar(20),
SearchTerm int,
TaxNumber int,
VAT int
);
INSERT INTO
#TempTable (CountryCode, CountryName, SearchTerm, TaxNumber, VAT)
VALUES
('AD', 'Andorra', 2, 3, 6),
('AL', 'Albania', 22, 32, 6),
('AM', 'Armenia', 24, 3, 66),
('AO', 'Angola', 11, 5, 9)
declare @sql nvarchar(max), @cols nvarchar(max)
select
@cols = Coalesce(@cols + ', ', '') + '[' + [name] + ']'
from tempdb.sys.columns
where object_id = Object_id('tempdb..#TempTable') and column_id >= 3
order by column_id
set @sql = '
Select CountryCode, CountryName, SAPFieldType, SAPField
into #ResultTempTable
from #TempTable
unpivot
(
SAPField for SAPFieldType in
(
'+@cols+'
)
) up
Order By SAPFieldType
'
exec (@sql)
SELECT * FROM #ResultTempTable
Briefly the issue is that inspite of adding the line:into #ResultTempTable
somehow the query not showing any result:SELECT * FROM #ResultTempTable
rather an error message that it does not exist: