Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a column with a string

Tags:

sql

sql-server

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 the name of column, but somehow it becomes a new value in the table. Can anyone help me understand what is going on?

like image 641
SwordW Avatar asked Feb 28 '26 05:02

SwordW


1 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)
like image 157
SQLChao Avatar answered Mar 02 '26 21:03

SQLChao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!