Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Dynamic SQL

Author  Topic 

Beginer2012
Starting Member

45 Posts

Posted - 2012-06-11 : 08:56:20
Hello,

Upon executing the following code I get this error:
-------------------------------------------------
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@MyCount".
-------------------------------------------------


I need to store the count in a variable dynamically to genrate complicated report.
Any sugestions ?

Thank you

DECLARE @MyCount INT
DECLARE @MyTable VARCHAR(10)
DECLARE @SqlCmd NVARCHAR(500)

SET @Mytable = 'test'

SET @SqlCmd = 'SELECT @MyCount =COUNT(*) FROM ' + @MyTable

EXECUTE (@SqlCmd)

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-06-11 : 09:22:42
You should use the sp_executesql interface to get data out from the dynamic SQL query. http://msdn.microsoft.com/en-us/library/ms188001.aspx

Your query would be something like this (untested):
DECLARE @MyCount INT
DECLARE @MyTable VARCHAR(10)
DECLARE @SqlCmd NVARCHAR(500)

SET @Mytable = 'test'

SET @SqlCmd = 'SELECT @TheCount =COUNT(*) FROM ' + @MyTable

EXEC sp_executesql
@stmt = @SqlCmd,
@params = N'@TheCount as int OUTPUT',
@TheCount = @MyCount OUTPUT;
select @MyCount;


Note, OUTPUT specified in two places. Also, I changed the variable name in the dynamic SQL to @TheCount just to show the distinction.

[Insert usual advice about avoiding dynamic sql if at all possible here]
Go to Top of Page

Beginer2012
Starting Member

45 Posts

Posted - 2012-06-11 : 09:25:18
Thank you very much for your help.
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2012-06-11 : 12:19:21
If all you need is a count of all rows in the table:
DECLARE @MyTable varchar(100), @MyCount bigint
SELECT @MyCount=rows FROM sys.partitions WHERE OBJECT_NAME(object_id)=@MyTable AND index_id<2
As sunita suggested, there's no dynamic SQL needed.
Go to Top of Page
   

- Advertisement -