How to select a column with a row

This is my code:

declare @MaxPointNumber INT=499, @pointNumber INT = 5;
select ('point'+CAST(@pointNumber as varchar))
from #TempHold

      

And this is the result: enter image description here

point5 should be a column name, but somehow it becomes a new value in the table. Can anyone help me understand what is going on?

+3


source to share


3 answers


As stated earlier you need dynamic sql



DECLARE @sql VARCHAR(200)
DECLARE @MaxPointNumber INT=499, @pointNumber INT = 5;
SET @sql = 'SELECT ' + ('point'+CAST(@pointNumber as varchar)) +
' from #TempHold'


EXEC (@sql)

      

+2


source


you choose from Tempold. it acts like a column name. the table you are retrieving from.



0


source


figured it out:

set @xxx=CAST(@pointNumber as varchar);
exec( 'select point'+ @xxx +' from #TempHold')

      

0


source







All Articles