June 11, 2012 at 6:55 am
Hello,
Upon executing the following code I get this error:
-------------------------------------------------
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@MtCount".
-------------------------------------------------
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)
June 11, 2012 at 7:05 am
You have declared a variable called @MyCount, but your Dynamic SQL is using a variable called @MtCount.
Dave
June 11, 2012 at 7:09 am
Sorry..I have updated the code..But still the same error message..
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@MyCount".
June 11, 2012 at 7:11 am
Beginner2012 (6/11/2012)
Hello,Upon executing the following code I get this error:
-------------------------------------------------
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@MtCount".
-------------------------------------------------
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 @MtCount =COUNT(*) FROM ' + @MyTable
EXECUTE (@SqlCmd)
Three problems with your code: -
1. You've typo'd the name of the variable.
2. The variable is declared in a different context to where you've attempted to assign it.
3. Please look into SQL injection, what you've posted is almost a "how-to" for writing vulnerable code.
Try something like this: -
DECLARE @MyCount INT, @MyTable VARCHAR(10), @SqlCmd NVARCHAR(500);
SET @MyTable = 'test'
SET @SqlCmd = 'SELECT @MtCountInner = COUNT(*) FROM ' + QUOTENAME(@MyTable);
EXECUTE sp_executesql @SqlCmd, N'@MtCountInner INT OUTPUT', @MtCountInner = @MyCount OUTPUT;
SELECT @MyCount;
June 11, 2012 at 7:12 am
The variable @MyCount is in a different scope to teh dynamic SQL that you have declared.
June 11, 2012 at 7:20 am
Dwayne Dibley (6/11/2012)
The variable @MyCount is in a different scope to teh dynamic SQL that you have declared.
Cadavre's call using sp_ExecuteSQL will take care of that particular nuance.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply