显示包含当前日期的列名称。

时间:2014-01-04 04:07:15

标签: sql-server

我尝试了以下脚本,但它不起作用。

DECLARE @STOCKDATE varchar(32)
SET @STOCKDATE = 'STOCK BALANCE AS OF ' + CAST(getdate() as varchar(32))

SELECT SUM(qty) as @STOCKDATE FROM.....

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用动态SQL,否则您无法从变量中指定别名:

DECLARE @STOCKDATE varchar(32)
SET @STOCKDATE = 'STOCK BALANCE AS OF ' + CAST(getdate() as varchar(32))

DECLARE @sql varchar(max)
SET @sql = 'SELECT SUM(qty) as [' + @STOCKDATE + '] FROM.....'
EXEC (@sql)

答案 1 :(得分:0)

@Szymon的答案是正确的,但只是一个小修改

DECLARE @STOCKDATE varchar(32)
SET @STOCKDATE = 'STOCK BALANCE AS OF ' + CAST(getdate() as varchar(32))

DECLARE @sql varchar(max)
SET @sql = 'SELECT SUM(qty) as ''' + @STOCKDATE + ''' FROM.....'
EXEC (@sql)

@STOCKDATE之前和之后添加2个单引号,这样变量就会毫无异常地传递