2

可能重复:
将动态 sql 的结果分配给变量

你能帮我在给定的例子中存储一个值吗?

DECLARE @variable VARCHAR(20)

declare @table_name varchar(20)='sample_table'

EXEC('SELECT '+@variable+'=SUM(CAST([Annual Plan & GM$] AS MONEY)) FROM '+@table_name+'')
4

1 回答 1

3

您可以使用以下命令返回类型化的输出参数sp_executesql

declare @variable   money
declare @table_name varchar(20)='sample_table'

declare @sql nvarchar(255) = 'SELECT @variable=SUM(CAST([Annual Plan & GM$] AS MONEY)) FROM '+ @table_name
EXEC sp_executesql @sql, 
    N'@variable money OUTPUT',
    @variable OUTPUT

select @variable
于 2013-01-18T12:37:01.877 回答