2014-06-10 59 views
-1

我曾設在這裏Table name as variable如何從EXEC結果存儲到@variable

我的問題是同一個問題,我怎麼能存儲結果從EXEC語句返回到@Variable?

實施例:

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

由於

+0

嘗試閱讀[此](http://stackoverflow.com/questions/803211/how-to-get -sp-executionql-result-into-a-variable)或[this](http://stackoverflow.com/questions/2245691/how-to-assign-an-exec-result-to-a-sql-variable) – Sky

+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, 
@[email protected] OUTPUT 
SELECT @COUNT