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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With