如何在列名中添加参数?

时间:2017-01-12 09:56:50

标签: sql-server tsql dynamic-sql

查询:

declare @Year  varchar(max) ;
SET @Year=  CAST(YEAR(GETDATE()) AS VARCHAR)
select 1 as 'apr-' + cast(@year as varchar(10))

错误:

  

Msg 102,Level 15,State 1,Line 3
  ' +'。

附近的语法不正确

输出如:

apr-2017
1

1 个答案:

答案 0 :(得分:1)

您可以使用动态SQL:

 declare @Year  varchar(max) ;
 SET @Year=  CAST(YEAR(GETDATE()) AS VARCHAR)

 declare @cmd nvarchar(max)
 select @cmd = 'select 1 as ''apr-' + cast(@year as varchar(10)) + ''''
 exec (@cmd)