SQL: Select dynamic column name based on variable
You could build your query into a string and use exec
CREATE PROCEDURE [My_Procedure]
@myDynamicColumn varchar(50)
AS BEGIN
EXEC('SELECT ''value'' AS ' + @myDynamicColumn)
END
EXEC ('SELECT ''value'' AS ' + @myDynamicColumn)
Both the upvoted answers are very dangerous here, both are wide open to injection attacks and should not be used.
When injecting dynamic object names you must ensure you properly quote your object names. SQL Server has a built in function for that, QUOTENAME
. Thus what you should actually be doing is the following:
CREATE PROCEDURE [My_Procedure] @myDynamicColumn sysname
AS BEGIN
DECLARE @SQL nvarchar(MAX) = N'SELECT ''value'' AS ' + QUOTENAME(@myDynamicColumn) + N';';
EXEC sys.sp_executesql @SQL;
END
You'll note I also change the data type of the parameter to sysname
, a synonym for nvarchar(128) NOT NULL
, which is the data type SQL Server uses internally for object names.