0

I had the same issue located here Table name as variable

My question is, how can I store the results returned from the EXEC statement into a @variable ?

Example:

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

Thanks

Community
  • 1
  • 1
realtek
  • 831
  • 4
  • 16
  • 36
  • Try reading [this](http://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable) or [this](http://stackoverflow.com/questions/2245691/how-to-assign-an-exec-result-to-a-sql-variable) – Sky Jun 10 '14 at 10:35
  • your question and example in different direction – Vignesh Kumar A Jun 10 '14 at 10:36

1 Answers1

1

write as:

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
Deepshikha
  • 9,896
  • 2
  • 21
  • 21