SQL Server Concatenate Strings to make column alias

mpgws1up  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(108)

I am trying to make a column alias that concatenates strings (one coming from a parameter).

I'm running the same query with different values on the parameter to generate my report to send out, and I want the parameter value included in the column headers/names so that it is clear to the end user (and to myself 30 seconds later) which parameter was used.

I'm trying something like this, but it won't execute

declare @fy int
set @fy = 2021

select 
    [Section Name],
    [Revenue] as concat(str(@fy),' Earned Revenue'),
    ...
    ...

A complete toy example for trying is like this (less stuff, lets just make the param a string

declare @fy nvarchar(4)
set @fy = '2021'

select 
    'asdf' as concat(@fy,' column')

I'm getting

Incorrect syntax near '@fy'.`

ltqd579y

ltqd579y1#

Names of database objects such as tables, columns, stored procedures, views, etc, can contain alphanumeric characters and must begin with an alphabet or an underscore, not with digit.

We need to use dynamic query to achieve dynamic column alias name.

DECLARE @fy INT = 2021; 
DECLARE @sql NVARCHAR(1000) = 'SELECT 1234 AS EarnedRevenue'+CAST(@fy AS NVARCHAR(4));
EXEC (@sql)

相关问题