David Holland
David Holland

Reputation: 1

Using a variable to name query results column

Is there a way to use a variable to name a column in SQL query results? My example below gives an "Incorrect syntax" error?

declare @ColumnName varchar(100) = 'Column 1'

Select CustomerNumber as @ColumnName
  from Customers

Upvotes: 0

Views: 42

Answers (1)

Rion Williams
Rion Williams

Reputation: 76557

Generally, SQL isn't going to handle defining variables to use as column aliases. This means you'll likely have to resort to using dynamic SQL, which involves building your query and then executing it manually via the sp_executesql procedure.

The following is an example of your existing query executed dynamically using SQL Server :

-- Define your variable
DECLARE @ColumnName VARCHAR(100) = 'Column 1'
-- Define your SQL query
DECLARE @SQL NVARCHAR(200) = 'SELECT CustomerNumber AS ' + @ColumnName + ' FROM Customers'
-- Execute your query dynamically
EXEC sp_executesql @SQL 

Upvotes: 1

Related Questions