0

我想使用我声明局部变量,例如as 子句

我得到去年和今年

declare @lastYear varchar(4)=datepart(YEAR,DATEADD(year,-1,GETDATE()));
declare @currentYear varchar(4)=datepart(YEAR,DATEADD(year,0,GETDATE()));

我想像上面一样使用,

select a.totalCountLy  as @lastYear,
a.totalCountLy as @currentYear from TableName as a (nolock

结果就像

2011          2012
------------------
1000          5000
400           1000

有什么建议么。谢谢。

4

1 回答 1

1

这个怎么样,使用动态SQL?

declare @lastYear varchar(4)=datepart(YEAR,DATEADD(year,-1,GETDATE()));

declare @sql nvarchar(max) = 
    N'select a.total as [' + convert(nvarchar(24), @lastYear) + N'] from TableName as a'

exec sp_executesql @sql
于 2012-05-22T13:22:30.063 回答