如何将EXEC的结果存储到@variable中

时间:2014-06-10 10:31:26

标签: sql sql-server

我遇到了同样的问题Table name as variable

我的问题是,如何将EXEC语句返回的结果存储到@variable?

示例:

EXEC('SELECT count(*) FROM ' + @tablename)

由于

1 个答案:

答案 0 :(得分:0)

写为:

DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @COUNT INT
DECLARE @TableName NVARCHAR(100)

SET @SQLString = N'SELECT @COUNTOUT = count(*) FROM ' + QUOTENAME(@TableName);

SET @ParmDefinition = N'@COUNTOUT INT OUTPUT'
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@COUNTOUT=@COUNT OUTPUT
SELECT @COUNT