我尝试了以下脚本,但它不起作用。
DECLARE @STOCKDATE varchar(32)
SET @STOCKDATE = 'STOCK BALANCE AS OF ' + CAST(getdate() as varchar(32))
SELECT SUM(qty) as @STOCKDATE FROM.....
我该怎么做?
答案 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个单引号,这样变量就会毫无异常地传递