Must declare the scalar variable sql ошибка

@RowFrom int

@RowTo int

are both Global Input Params for the Stored Procedure, and since I am compiling the SQL query inside the Stored Procedure with T-SQL then using Exec(@sqlstatement) at the end of the stored procedure to show the result, it gives me this error when I try to use the @RowFrom or @RowTo inside the @sqlstatement variable that is executed.. it works fine otherwise.. please help.

"Must declare the scalar variable "@RowFrom"."

Also, I tried including the following in the @sqlstatement variable:

'Declare @Rt int'
'SET @Rt = ' + @RowTo

but @RowTo still doesn’t pass its value to @Rt and generates an error.

hofnarwillie's user avatar

hofnarwillie

3,55310 gold badges48 silver badges73 bronze badges

asked Aug 24, 2011 at 20:39

bill's user avatar

1

You can’t concatenate an int to a string. Instead of:

SET @sql = N'DECLARE @Rt int; SET @Rt = ' + @RowTo;

You need:

SET @sql = N'DECLARE @Rt int; SET @Rt = ' + CONVERT(VARCHAR(12), @RowTo);

To help illustrate what’s happening here. Let’s say @RowTo = 5.

DECLARE @RowTo int;
SET @RowTo = 5;

DECLARE @sql nvarchar(max);
SET @sql = N'SELECT ' + CONVERT(varchar(12), @RowTo) + ' * 5';
EXEC sys.sp_executesql @sql;

In order to build that into a string (even if ultimately it will be a number), I need to convert it. But as you can see, the number is still treated as a number when it’s executed. The answer is 25, right?

In your case you can use proper parameterization rather than use concatenation which, if you get into that habit, you will expose yourself to SQL injection at some point (see this and this:

SET @sql = @sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;';

EXEC sys.sp_executesql @sql,
  N'@RowFrom int, @RowTo int',
  @RowFrom, @RowTo;

answered Aug 24, 2011 at 21:01

Aaron Bertrand's user avatar

Aaron BertrandAaron Bertrand

272k36 gold badges465 silver badges487 bronze badges

4

You can also get this error message if a variable is declared before a GOand referenced after it.

See this question and this workaround.

answered Mar 25, 2019 at 22:11

Pierre C's user avatar

Pierre CPierre C

2,76035 silver badges32 bronze badges

Just FYI, I know this is an old post, but depending on the database COLLATION settings you can get this error on a statement like this,

SET @sql = @Sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;';

if for example you typo the S in the

SET @sql = @***S***ql 

sorry to spin off the answers already posted here, but this is an actual instance of the error reported.

Note also that the error will not display the capital S in the message, I am not sure why, but I think it is because the

Set @sql =

is on the left of the equal sign.

answered Apr 1, 2015 at 19:13

htm11h's user avatar

htm11hhtm11h

1,7298 gold badges46 silver badges103 bronze badges

0

This is most likely not an answer to the issue itself, but this question pops up as first result when searching for Sql declare scalar variable hence I want to share a possible solution to this error.

In my case this error was caused by the use of ; after a SQL statement. Just remove it and the error will be gone.

I guess the cause is the same as @IronSean already posted in a comment above:

it’s worth noting that using GO (or in this case ;) causes a new branch where declared variables aren’t visible past the statement.

For example:

DECLARE @id int
SET @id = 78

SELECT * FROM MyTable WHERE Id = @var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = @var

answered Nov 5, 2020 at 16:25

ViRuSTriNiTy's user avatar

ViRuSTriNiTyViRuSTriNiTy

5,0072 gold badges31 silver badges56 bronze badges

5

Sometimes, if you have a ‘GO’ statement written after the usage of the variable, and if you try to use it after that, it throws such error. Try removing ‘GO’ statement if you have any.

answered May 24, 2021 at 6:12

Sunita Rani Nayak's user avatar

Just adding what fixed it for me, where misspelling is the suspect as per this MSDN blog…

When splitting SQL strings over multiple lines, check that that you are comma separating your SQL string from your parameters (and not trying to concatenate them!) and not missing any spaces at the end of each split line. Not rocket science but hope I save someone a headache.

For example:

db.TableName.SqlQuery(
    "SELECT Id, Timestamp, User " +
    "FROM dbo.TableName " +
    "WHERE Timestamp >= @from " +
    "AND Timestamp <= @till;" + [USE COMMA NOT CONCATENATE!]
    new SqlParameter("from", from),
    new SqlParameter("till", till)),
    .ToListAsync()
    .Result;

EBH's user avatar

EBH

10.3k3 gold badges32 silver badges59 bronze badges

answered Jun 21, 2017 at 15:46

Tim Tyler's user avatar

Tim TylerTim Tyler

2,3112 gold badges15 silver badges13 bronze badges

1

Case Sensitivity will cause this problem, too.

@MyVariable and @myvariable are the same variables in SQL Server Man. Studio and will work. However, these variables will result in a «Must declare the scalar variable «@MyVariable» in Visual Studio (C#) due to case-sensitivity differences.

answered Jun 9, 2016 at 11:20

Hans M Ohio's user avatar

Just an answer for future me (maybe it helps someone else too!). If you try to run something like this in the query editor:

USE [Dbo]
GO

DECLARE @RC int

EXECUTE @RC = [dbo].[SomeStoredProcedure] 
   2018
  ,0
  ,'arg3'
GO

SELECT month, SUM(weight) AS weight, SUM(amount) AS amount 
FROM SomeTable AS e 
WHERE year = @year AND type = 'M'

And you get the error:

Must declare the scalar variable «@year»

That’s because you are trying to run a bunch of code that includes BOTH the stored procedure execution AND the query below it (!). Just highlight the one you want to run or delete/comment out the one you are not interested in.

marc_s's user avatar

marc_s

729k175 gold badges1327 silver badges1455 bronze badges

answered Jul 21, 2019 at 18:05

saiyancoder's user avatar

saiyancodersaiyancoder

1,2752 gold badges13 silver badges20 bronze badges

If someone else comes across this question while no solution here made my sql file working, here’s what my mistake was:

I have been exporting the contents of my database via the ‘Generate Script’ command of Microsofts’ Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of «GO» statements in the sql file.

What I didn’t know was that variables declared at the top of a file aren’t accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error «Must declare the scalar variable xy» was gone!

answered Oct 19, 2020 at 10:33

pbur's user avatar

pburpbur

757 bronze badges

As stated in https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-go?view=sql-server-ver16 , the scope of a user-defined variable is batch dependent .

—This will produce the error

 GO   
    DECLARE @MyVariable int;
    SET @MyVariable = 1;
    GO --new batch of code
    SELECT @MyVariable--CAST(@MyVariable AS 
    int);
 GO

—This will not produce the error

 GO   
   DECLARE @MyVariable int;
   SET @MyVariable = 1;
   SELECT @MyVariable--CAST(@MyVariable AS int);
 GO

We get the same error when we try to pass a variable inside a dynamic SQL:

GO
DECLARE @ColumnName VARCHAR(100),
        @SQL NVARCHAR(MAX);
SET @ColumnName = 'FirstName';
EXECUTE ('SELECT [Title],@ColumnName FROM Person.Person');  
GO

—In the case above @ColumnName is nowhere to be found, therefore we can either do:

EXECUTE ('SELECT [Title],' +@ColumnName+ ' FROM Person.Person');

or

GO
DECLARE @ColumnName VARCHAR(100),
        @SQL NVARCHAR(MAX);
SET @ColumnName = 'FirstName';
SET @SQL = 'SELECT ' + @ColumnName + ' FROM Person.Person';
EXEC sys.sp_executesql @SQL  
GO

answered Sep 15, 2022 at 10:39

Mihnea Andrei Ciorica's user avatar

Give a ‘GO’ after the end statement and select all the statements then execute

answered Dec 29, 2021 at 15:23

Srestha Chakraborty's user avatar

1

This article lists out the extensive list of scenarios in which we get the following error message and how to resolve it.

Error Message:

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable “%.*ls”.

Root Cause:

This error occurs if we are trying to use an undeclared variable

Below are the couple of scenarios in which we come across this error and how to resolve it.

Scenario 1: Trying to use an undeclared variable

Try executing the below statement

PRINT @AuthorName

RESULT:

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable “@AuthorName”.

Reason for this error: In the above example, the variable @AuthorName is used in the PRINT statement without declaring it, which is not allowed by Sql Server.

Solution:Declare the @AuthorName variable before using it in the PRINT statement as below:

DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar'
PRINT @AuthorName

RESULT:
Error Message 128

Scenario 2: Trying to use a local declared variable after batch separator GO statement

Try executing the below statement

DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar'
PRINT @AuthorName
GO
PRINT @AuthorName

RESULT:

Basavaraj Biradar
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable “@AuthorName”.

Reason for this error: In the above example, the variable @AuthorName is used in the PRINT statement after the batch separator GO Statement. Basically the scope of the local variables is within the batch in which it is declared.

Solution:Re-declare the @AuthorName variable before using it in the PRINT statement after the GO statement as below:

DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar'
PRINT @AuthorName
GO
DECLARE @AuthorName VARCHAR(100) = 'Basava'
PRINT @AuthorName

RESULT:
Error Message 137

Scenario 3: Using local declared variable in the dynamic sql statement executed by the EXECUTE statement

Try executing the below statement

DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar'
EXECUTE ('PRINT @AuthorName')

RESULT:

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable “@AuthorName”.

Reason for this error: In the above example, the variable @AuthorName is used in the statement executed by EXECUTE statement. EXECUTE statement doesn’t have the visibility of the variables declared outside of it.

Solution: We can rewrite the above statements as below to resolve this issue:

DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar'
EXECUTE ('PRINT ''' + @AuthorName + '''' )

RESULT:
Must declare the scalar variable

Alternative solution: One more alternative solution for the above problem, is to use the SP_EXECUTESQL statement which allows parameterized statement as below:

DECLARE @AuthorName VARCHAR(100) = 'Basavaraj Biradar'
EXECUTE SP_EXECUTESQL N'PRINT @AuthorName',
           N'@AuthorName VARCHAR(100)',@AuthorName

RESULT:
Must declare the scalar variable SP_EXECUTESQL

Let me know if you have encountered this error in any other scenario.

  • Remove From My Forums
  • Question

  • Why does the code block below tell me that I must declare the scalar variable "@AddWhere"?

    DECLARE @SQL NVARCHAR (MAX) SET @SQL = ' Declare @DateFrom INT set @DateFrom = 20120409 Declare @DateTo INT set @DateTo = 20120411 DECLARE @StoreNo NVARCHAR(5) SET @StoreNo = ''00013'' Declare @DealerID NVARCHAR(12) Set @DealerID = ''zxcvbn'' Declare @AddWhere NVARCHAR(MAX) IF @StoreNo = '' BEGIN SET @AddWhere = '''' END ELSE BEGIN SET @AddWhere = ''AND (c.Serial_Number IN (SELECT MAX(Serial_Number) AS Serial_Number FROM (SELECT Serial_Number, SUBSTRING(Customer_ID, 3, 5) AS Customer_ID FROM dbo.Customers AS c WHERE (Class_Code = N''XYZ'')) AS customer WHERE (Customer_ID = '' +@storeno+''))) END SELECT TOP (100) PERCENT CASE dt.Dealer_ID WHEN ''bnmkl'' THEN SUBSTRING(dt.DEALER_ID, 4, 2) ELSE SUBSTRING(dt.DEALER_ID, 5, 1) END AS DIV, SUBSTRING(dt.Dealer_ID, 7, 2) AS REG, SUBSTRING(dt.Dealer_ID, 10, 3) AS DIST, SUBSTRING(c.Customer_ID, 3, 5) AS StoreNo, c.PostCode, c.Time_Zone, d.Day_Text, d.Date_Text, t.Time_Text_12_Hour, a.Event_Name, a.Area, a.User_Name, a.User_Number FROM dbo.CustomerActivity AS a INNER JOIN dbo.Customers AS c ON a.Customer_Key = c.Customer_Key INNER JOIN (SELECT Dealer_Key, Parent_Dealer_Key, Dealer_ID, Parent_Dealer_ID, [Level], Has_Subdealers FROM dbo.DealerTree(@DealerID, 1, 0) AS DealerTree_1) AS dt ON c.Dealer_ID = dt.Dealer_ID INNER JOIN dbo.Dates AS d ON a.Event_Date_Key = d.Date_Key INNER JOIN dbo.Times AS t ON a.Event_Time_Key = t.Time_Key WHERE (a.Open_Close_Signal = 1) AND (a.Event_Name NOT IN (''LATE-TO-CLOSE'', ''CANCEL'', ''LATE-TO-OPEN'')) AND (d.Date_Key BETWEEN @DateFrom AND @DateTo) AND (c.Class_Code = ''XYZ'') ' + @AddWhere+' ORDER BY DIV, REG, DIST, c.Customer_ID, t.Time' --PRINT @SQL execute sp_executesql @SQL


    Lee Markum

    • Edited by

      Thursday, August 30, 2012 8:27 PM

Answers

  • Declare the parameters outside 

    DECLARE
    @SQL
    NVARCHAR
    (MAX)

    Declare @AddWhere NVARCHAR(MAX)

    Your query should be something like this : not 100% if it works but try :

    Convert the date formats accordingly as per your req:

    DECLARE @SQL NVARCHAR (MAX)   
    Declare @DateFrom date
    set @DateFrom = ‘20120409’
    Declare @DateTo date
    set @DateTo = ‘20120411’
    DECLARE @StoreNo NVARCHAR(5)
    SET @StoreNo = ‘00013’
    Declare @DealerID NVARCHAR(12)
    Set @DealerID = ‘zxcvbn’
    Declare @AddWhere NVARCHAR(MAX) 

    SET @SQL = ‘
    IF @StoreNo = »
    BEGIN
    SET @AddWhere = »»

        END 

        
        ELSE 
    BEGIN
    SET @AddWhere = »AND (c.Serial_Number IN
                              (SELECT     MAX(Serial_Number) AS Serial_Number
                                FROM          (SELECT     Serial_Number, SUBSTRING(Customer_ID, 3, 5) AS Customer_ID
                                                        FROM          dbo.Customers AS c
                                                        WHERE      (Class_Code = N»XYZ»)) AS customer
                                WHERE      (Customer_ID = ‘+@storeno+’)))
    END

    SELECT     TOP (100) PERCENT CASE dt.Dealer_ID WHEN »bnmkl» THEN SUBSTRING(dt.DEALER_ID, 4, 2) ELSE SUBSTRING(dt.DEALER_ID, 5, 1) END AS DIV, 
                          SUBSTRING(dt.Dealer_ID, 7, 2) AS REG, SUBSTRING(dt.Dealer_ID, 10, 3) AS DIST, SUBSTRING(c.Customer_ID, 3, 5) AS StoreNo, c.PostCode, c.Time_Zone, 
                          d.Day_Text, d.Date_Text, t.Time_Text_12_Hour, a.Event_Name, a.Area, a.User_Name, a.User_Number
    FROM         dbo.CustomerActivity AS a INNER JOIN
                          dbo.Customers AS c ON a.Customer_Key = c.Customer_Key INNER JOIN
                              (SELECT     Dealer_Key, Parent_Dealer_Key, Dealer_ID, Parent_Dealer_ID, [Level], Has_Subdealers
                                FROM          dbo.DealerTree(‘+@DealerID+’, 1, 0) AS DealerTree_1) AS dt ON c.Dealer_ID = dt.Dealer_ID INNER JOIN
                          dbo.Dates AS d ON a.Event_Date_Key = d.Date_Key INNER JOIN
                          dbo.Times AS t ON a.Event_Time_Key = t.Time_Key
    WHERE     (a.Open_Close_Signal = 1) AND (a.Event_Name NOT IN (»LATE-TO-CLOSE», »CANCEL», »LATE-TO-OPEN»)) AND (d.Date_Key BETWEEN’+ @DateFrom + ‘AND’ +@DateTo +’) AND 
                          (c.Class_Code = »XYZ») ‘ + @AddWhere+’

                          
    ORDER BY DIV, REG, DIST, c.Customer_ID, t.Time’

    • Edited by
      JR1811
      Thursday, August 30, 2012 9:08 PM
    • Proposed as answer by
      Naomi N
      Friday, August 31, 2012 8:14 PM
    • Marked as answer by
      Kalman Toth
      Tuesday, September 4, 2012 6:38 PM

Trying to update two tables (City and Location) using two table variables (@NameZip, @NameZip2). The city names have ZipCodes and ZipCodes have Names instead of vice versa. Updates are changing City names and ZipCodes where they were wrongly entered. But getting the error:

Msg 137, Level 16, State 1, Line 28
Must declare the scalar variable «@NameZip2».

Msg 137, Level 16, State 1, Line 32
Must declare the scalar variable «@NameZip».

The query I wrote:

--first table variable
DECLARE @NameZip TABLE 
                 (
                     Zip_Code NVARCHAR(100),
                     Name NVARCHAR(100),
                     id_city INT
                 )

--second table variable
DECLARE @NameZip2 TABLE
                  (
                      Zip_Code nvarchar(100),
                      Name NVARCHAR(100),
                      id_city INT
                  )

--inserting into first table variable from City and Location table
INSERT INTO @NameZip (Zip_code, Name, id_city)
    SELECT B.Zip_Code, A.Name, A.id_city
    FROM City A 
    INNER JOIN Location B ON A.id_city = B.id_city 
                          AND Name NOT LIKE '%[^0-9]%'

--inserting into second table variable from first table variable
INSERT INTO @NameZip2(Zip_code, Name, id_city)
    SELECT Name, Zip_Code, id_city
    FROM @NameZip

UPDATE City 
SET Name = (SELECT Name FROM @NameZip2)
WHERE City.id_city = @NameZip2.id_city -- I get error on this line

UPDATE Location
SET Zip_Code = (SELECT Zip_Code FROM @NameZip2)
WHERE Zip_Code = @NameZip.Zip_Code -- I get error on this line

Any inputs regarding this would be appreciated.


Posted by Marta on March 17, 2023

Viewed 386 times

Card image cap

If you’re working with SQL Server or any other relational database management system, you may encounter an error message that says “Must declare the scalar variable” when executing a query.

This error occurs when the query references a variable that has not been declared or is out of scope.

In this article, we will discuss what this error is and how to fix this error with code examples.

What is the error “Must Declare the Scalar Variable”?

The error message “Must declare the scalar variable” is a common error in programming, particularly in SQL. This error typically occurs when a variable is used in a query or command but has not been declared or defined.

In SQL, a scalar variable is a variable that can hold a single value, such as an integer, string, or date. When using a scalar variable in a query, the variable must be declared before it can be used.

If the variable is not declared, the system will not recognize the variable, resulting in the error message “Must declare the scalar variable.”

For example, consider the following SQL query:

SELECT * FROM Customers WHERE CustomerID = @CustID

In this query, the variable @CustID is being used to retrieve a specific customer’s information from the Customers table. However, if the variable has not been declared, the system will not know what @CustID refers to, resulting in the “Must declare the scalar variable” error.

Three Steps to fix it

Declare the variable

The first step in fixing the “Must declare the scalar variable” error is to declare the variable. The variable declaration should be done before using it in the query. For example, consider the following query:

SELECT *
FROM Customers
WHERE FirstName = @FirstName

In this query, the variable @FirstName is referenced, but it has not been declared. To fix this, we need to declare the variable as follows:

DECLARE @FirstName VARCHAR(50)
SET @FirstName = 'John'

SELECT *
FROM Customers
WHERE FirstName = @FirstName

In this example, we declared the variable @FirstName as a VARCHAR with a length of 50 and assigned it the value ‘John’. Now we can use this variable in the query.

Check the variable scope

If the variable has been declared but you’re still getting the “Must declare the scalar variable” error, then it could be because the variable is out of scope. For example, consider the following code:

DECLARE @FirstName VARCHAR(50)

IF @FirstName = 'John'
BEGIN
    SELECT *
    FROM Customers
    WHERE FirstName = @FirstName
END

In this example, we declared the variable @FirstName, but it is out of scope when we reference it inside the IF block. To fix this, we need to declare the variable inside the IF block as follows:

DECLARE @FirstName VARCHAR(50)

IF @FirstName = 'John'
BEGIN
    DECLARE @FirstName VARCHAR(50)
    SET @FirstName = 'John'

    SELECT *
    FROM Customers
    WHERE FirstName = @FirstName
END

In this example, we declared the variable @FirstName inside the IF block and assigned it the value ‘John’. Now we can use this variable in the query.

Use parameterized queries

Another way to avoid the “Must declare the scalar variable” error is to use parameterized queries. Parameterized queries are a way of passing values to a query in a secure and efficient manner. For example, consider the following parameterized query:

DECLARE @FirstName VARCHAR(50) = 'John'

SELECT *
FROM Customers
WHERE FirstName = @FirstName

In this example, we declared the variable @FirstName and assigned it the value ‘John’. We then used this variable in the query. The difference between this example and the first example is that we used a parameterized query instead of a variable in the WHERE clause.

Conclusion

In conclusion, the “Must declare the scalar variable” error occurs when a query references a variable that has not been declared or is out of scope.

To fix this error, you can declare the variable, check the variable scope, or use parameterized queries. By following these steps, you can ensure that your queries execute without any errors.

I hope this article was useful, and thanks for reading and supporting this blog!

More Interesting Articles

cyber security certificates
finish coding project faster
companies that use java

  • Multitronics код ошибки 504
  • Multitronics как посмотреть ошибки
  • Multitronics x150 расшифровка ошибок
  • Multitronics x150 коды ошибок
  • Multitronics x115 как сбросить ошибки