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.
| 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 1Must declare the scalar variable "@MyCount".-------------------------------------------------I need to store the count in a variable dynamically to genrate complicated report.Any sugestions ?Thank youDECLARE @MyCount INTDECLARE @MyTable VARCHAR(10)DECLARE @SqlCmd NVARCHAR(500)SET @Mytable = 'test' SET @SqlCmd = 'SELECT @MyCount =COUNT(*) FROM ' + @MyTableEXECUTE (@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.aspxYour query would be something like this (untested):DECLARE @MyCount INTDECLARE @MyTable VARCHAR(10)DECLARE @SqlCmd NVARCHAR(500)SET @Mytable = 'test'SET @SqlCmd = 'SELECT @TheCount =COUNT(*) FROM ' + @MyTableEXEC 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] |
 |
|
|
Beginer2012
Starting Member
45 Posts |
Posted - 2012-06-11 : 09:25:18
|
| Thank you very much for your help. |
 |
|
|
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 bigintSELECT @MyCount=rows FROM sys.partitions WHERE OBJECT_NAME(object_id)=@MyTable AND index_id<2 As sunita suggested, there's no dynamic SQL needed. |
 |
|
|
|
|
|