If all columns in the table are of the same data type (or compatible data types), then you can use a case expression like in the example below:DECLARE @colname NVARCHAR(64) = 'col2';
SELECT
CASE @colname
WHEN 'col1' THEN id1
WHEN 'col2' THEN id2
WHEN 'col3' THEN id3
END
FROM
YourTableName;
If the columns are incompatible data types, then you would have to use dynamic SQL. Dynamic SQL is susceptible to SQL inject attacks; The IF EXISTS clause in the query is to guard against that:DECLARE @colname NVARCHAR(64) = 'col7';
DECLARE @sql NVARCHAR(4000);
SET @sql = 'SELECT '+@colname+ ' FROM YourTableName';
IF EXISTS
( SELECT * FROM INFORMATION_SCHEMA.[COLUMNS] c
WHERE c.TABLE_NAME = 'YourTableName'
AND c.COLUMN_NAME = @colName
)
EXEC (@sql);