3

Here is what I have so far. I want to store the query result into an int variable but I get null so far. After execute, both @query and @countrow are both null. Any suggestion would be great.

 SET @query = N'select @countrow=count(*) from ' + @tablename EXECUTE sp_executesql @query 
1
  • If @query is null, then @tablename must be null Commented Oct 10, 2012 at 14:44

2 Answers 2

3
DECLARE @i INT, @sql NVARCHAR(512), @tablename varchar(200) = 'tbl' SET @sql = N'SELECT @i = COUNT(*) FROM ' + @tablename EXEC sp_executesql @query = @sql, @params = N'@i INT OUTPUT', @i = @i OUTPUT PRINT @i 

Take a look at SQL Fiddle

Sign up to request clarification or add additional context in comments.

Comments

2

You need to use the OUTPUT keyword, similar to this:

declare @query nvarchar(max) declare @countrow int declare @tablename varchar(50) SET @query = N'select @cnt=count(*) from ' + @tablename EXECUTE sp_executesql @query, N'@cnt int OUTPUT', @cnt=@countrow OUTPUT select @countrow as countrow -- to get the result 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.