I am attempting to dynamically select my columns from a table (dbo.Ordinal) which lists every column and it's position. These column headings correspond to the table Y2.
DECLARE
@ord int = 1,
@colname varchar(max),
@div varchar(max) = '',
@sql varchar (max)
WHILE @ord < 3 BEGIN
SET @ord = @ord + 1
Set @colname = '(SELECT BR FROM dbo.[Ordinal] WHERE ORDINAL_POSITION=' +CAST(@ord AS Varchar(10))+')'
SET @div = @div + ',' +(@colname)
END
Set @sql = '(SELECT Simulation' + @div + ' FROM dbo.[Y2 HR]) ORDER BY Simulation'
EXECUTE (@sql)
This code currently fills the resulting table with the column title I am trying to select. Ideally i'd like to see @div producing a text string opf the desired columns that can then be used in @sql,
Currently if I print @sql, the output is :
(SELECT Simulation,(SELECT BR FROM dbo.[Ordinal] WHERE ORDINAL_POSITION=2),(SELECT BR FROM dbo.[Ordinal] WHERE ORDINAL_POSITION=3) FROM dbo.[Y2 HR]) ORDER BY Simulation.
Any way to achieve this or suggestions for a different approach are welcome
Thanks