Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : CAST within EXEC (Dynamic SQL)

Tags:

sql

sql-server

I'm trying to dynamically compute a column name, however SQL Server doesn't let this happen. Is there a correct way of doing this?

Expected result

SELECT Column_1
FROM Table

Query

DECLARE @param AS INT;
SELECT @param = 1;

EXEC('SELECT Column_' + CAST(@param AS VARCHAR) + ' FROM Table');

Catch: the @Param needs to be int, for convenience of providing input.

like image 446
tempidope Avatar asked Feb 15 '26 23:02

tempidope


1 Answers

Please use like this

DECLARE @param AS INT;
SELECT @param=1;
DECLARE @SQL AS VARCHAR(MAX) = 'SELECT Column_'+CAST(@param AS VARCHAR(5))+' FROM Table'
EXEC(@SQL);
like image 70
Pawan Kumar Avatar answered Feb 18 '26 11:02

Pawan Kumar



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!