Error code 1327 undeclared variable

When I try to execute following query: SELECT id_subscriber INTO newsletter_to_send FROM subscribers I get an error: #1327 - Undeclared variable: newsletter_to_send What is wrong with that

When I try to execute following query:

SELECT id_subscriber
  INTO newsletter_to_send
  FROM subscribers 

I get an error:

#1327 — Undeclared variable: newsletter_to_send

What is wrong with that query ?

Clomp's user avatar

Clomp

2,9882 gold badges22 silver badges35 bronze badges

asked Jun 1, 2010 at 12:19

hsz's user avatar

1

I think you can follow my given way and hopefully you will be able to fix your problem.

At first use this sql command to create a new table where you want to take backup

CREATE TABLE destination_table_name LIKE source_table_name;

After then you can use this command to copy those data

INSERT INTO destination_table_name
SELECT * FROM source_table_name;

If you already have previous data in your Destination table ,
Firstly you can use this command

TRUNCATE TABLE destination_table_name; 

Thanks By
Md. Maruf Hossain

answered Jul 17, 2012 at 10:23

Md. Maruf Hossain's user avatar

0

CREATE TABLE table_name
AS  
SELECT ...(your select)

answered Dec 10, 2012 at 18:42

Fabiano Shark's user avatar

1

MySQL does not support SELECT INTO [table]. It only supports SELECT INTO [variable] and can only do this one variable at a time.

What you can do, however is use the CREATE TABLE syntax with a SELECT like so:

CREATE TABLE bar ([column list]) SELECT * FROM foo;

answered Jun 1, 2010 at 12:24

amphetamachine's user avatar

amphetamachineamphetamachine

26.7k11 gold badges59 silver badges72 bronze badges

2

I tried working on this just now and this works for me:

CREATE TABLE New_Table_name
SELECT * FROM Original_Table_name;

El Gucs's user avatar

El Gucs

8648 silver badges15 bronze badges

answered May 9, 2013 at 8:18

user2365440's user avatar

0

MySQL Server doesn’t support the SELECT … INTO TABLE Sybase SQL extension. Instead, MySQL Server supports the INSERT INTO … SELECT standard SQL syntax, which is basically the same thing. See Section 12.2.5.1, “INSERT … SELECT Syntax”.

Ref:- this

answered Jun 1, 2010 at 12:23

Salil's user avatar

SalilSalil

46k21 gold badges123 silver badges155 bronze badges

mysql don’t support SELECT … INTO … syntax,

if it’s a new table, use CREATE TABLE … SELECT … syntax.

example:

CREATE TABLE artists_and_works
  SELECT artist.name, COUNT(work.artist_id) AS number_of_works
  FROM artist LEFT JOIN work ON artist.id = work.artist_id
  GROUP BY artist.id;

read more here create-table-select

answered Feb 1, 2018 at 2:57

Dl Li's user avatar

Dl LiDl Li

363 bronze badges

If you want to create a new table as a Duplicate table.

CREATE TABLE WorkerClone LIKE Worker;   //only structure will show no data
CREATE TABLE WorkerClone Select * from  Worker; //DUPLICATE table created with all details.

Tanveer Badar's user avatar

answered Nov 24, 2019 at 7:29

Prakash Singh's user avatar

You can do this without CREATE TABLE + INSERT INTO + DROP TABLE Like this:

SELECT @newsletter_to_send := id_subscriber
FROM subscribers WHERE your_condition = your_value;

answered Jul 11, 2021 at 1:23

MTK's user avatar

MTKMTK

3,1482 gold badges31 silver badges49 bronze badges

MySQL does not support SELECT INTO [table]. It only supports SELECT INTO [variable] and can only do this one variable at a time.

What you can do, however is use the CREATE TABLE syntax with a SELECT like so:

Nikolay K's user avatar

Nikolay K

3,7003 gold badges29 silver badges37 bronze badges

answered Dec 23, 2011 at 7:38

siddu's user avatar

Ads were blocked — no problem. But keep in mind that developing HeidiSQL,
user support and hosting takes time and money. You may want to
send a donation instead.

Hi I’m running the following statement:

SELECT * INTO empl1 FROM empleado WHERE id_dep=1

Where it is supporsed that it will create a new table called empl1, this is to break one table in one more table, when I execute it I get the error message 1327 Undeclared variable.

Thank you

This syntax is for assigning values to a variable, whereas empl1 is a system variable which you cannot declare. Instead, you could SELECT * INTO @empl1 ... to set a session variable. SELECT @empl1 afterwards will show you the content.

What you want is likely such a script:

CREATE TABLE empl1 LIKE empl;
INSERT INTO empl1 SELECT * FROM empl;

Please login to leave a reply, or register at first.

This page uses cookies to show you non-personalized advertising and server usage statistic diagrams.

What is must declare the scalar variable errorMust declare the scalar variable error is a common occurrence for coders. There are several causes for this error. For instance, if the error precedes the term “<Variable Name>,” it might suggest a local variable is used in a stored procedure within a script. To learn more about the error and its solutions, read the full article.

Contents

  • What Must Declare the Scalar Variable Error Means?
    • – Scalar Variable Declaration
  • What’s the Right Way to Declare a Variable in SQL?
    • – Scalar Variable Error SQL Example
  • Scalar Variable Warning Causes and Reasons
    • – Using an Undeclared Variable
    • – Local Declared Variable After Go Statement
    • – Execute a Local Declared Variable in Dynamic SQL Statement
  • The Best Fixes for Scalar Variable Failure
    • – Solving Undeclared Variable
    • – Go Statement or Batch Separator Fix
    • – Solving Local Declared Variable in Dynamic SQL Statement
    • – Other Causes and Fixes of Undeclared Variable
  • Must Declare the Scalar Variable Stored Procedure
  • Conclusion

Must Declare the Scalar Variable means that DECLARE statement wasn’t used to declare the function in a query. From the error stated above, there is a local variable within the function, script, or stored procedure that must be used with the Declare statement.

– Scalar Variable Declaration

The scalar variable declaration specifies the name of the variable’s data type and allocates its storage. Besides, the declaration can also assign an initial value and impose the NOT NULL constraint. So, the variable stores values with no internal components, and the value can change. In addition, to reference it, use the variable’s name.

Syntax:

What’s the Right Way to Declare a Variable in SQL?

To declare a variable in SQL, use the DECLARE statement. This function specifies some or all of the attributes of a name. In SQL, the Declare function initializes a variable by assigning it a name and a data type. A variable name must start with the @ sign.

The below example declares a variable @modelYear

DECLARE @modelYear SMALLINT;

The data type of the @modelYear variable is SMALLINT. When a variable is declared, its value is set to NULL by default. You can add an optional keyword AS between variable name and data type, as shown in the example below:

DECLARE @modelYear AS SMALLINT;

If you have several variables to declare, use commas to separate them, as shown below:

DECLARE @modelYear SMALLINT,

@productName VARCHAR(MAX);

If you don’t declare a variable, you will receive the error: Must declare the scalar variable name.

– Scalar Variable Error SQL Example

A variable declaration will specify the name and data type of the variable. Still, a variable declaration will be an initial value for most data types.

The variable name should be a valid user-defined identifier. Here is an example on how you can declare it:

DECLARE
partNumber NUMBER(8);
partName VARCHAR2(30);
inStock BOOLEAN;
partPrice NUMBER(8,3);
partDescription VARCHAR2(40);
BEGIN
NULL;
END;
/

Also, you can declare a variable and constant with initial values as shown below:

DECLARE
hoursWorked INTG := 50;
employeeCount INTG := 0;
pi CONSTANT REAL := 3.14159;
radius REAL := 6;
area REAL := (pi * radius**6);
BEGIN
NULL;
END;
/

If you do not define an initial value for a variable, assign a value to it prior to using it in any other context.

You can impose the NOT NULL constraint on a scalar variable. This constraint prevents assigning a null value to the item.

The item can acquire this constraint either implicitly or explicitly.

Scalar Variable Warning Causes and Reasons

This error will occur in most cases if you try to use an undeclared variable. Let’s look at some scenarios that might lead to this error.

– Using an Undeclared Variable

If you do not declare a variable, you will receive this error message. The following example attempts to execute a statement without declaring it.

The error must declare the scalar variable @AuthorName pops out when executing the statement. The primary reason for the error is that the variable @AuthorName is used in the PRINT statement without declaring it. The SQL server does not allow this approach.

– Local Declared Variable After Go Statement

This scenario will also throw the error. Here is an example to illustrate every step that leads to the issue:

DECLARE @AuthorName VARCHAR(100) = ‘Vishal Balasubramanian’
PRINT @AuthorName
GO
PRINT @AuthorName

When you execute the statement, the output will be:

Must declare the scalar variable “@AuthorName.”

So, what’s wrong? In this example, the variable @AuthorName is used after the batch separator GO Statement in the PRINT statement—the scope of the local variables in the batch in which it is declared.

– Execute a Local Declared Variable in Dynamic SQL Statement

Dynamic SQL lets you create SQL statements dynamically at runtime. You can create more general-purpose and flexible statements, as the full text of the SQL statements may be unknown at compilation. However, errors can occur if not well executed. Check the example below:

DECLARE @AuthorName VARCHAR(100) = ‘Vishal Balasubramanian’
EXECUTE (‘PRINT @AuthorName’)

You will get the must declare scalar variable “@AuthorName” error when you run the code.

Typically, the variable @AuthorName is used in the statement executed by EXECUTE statement. EXECUTE statement does not have the visibility of the variables declared outside it. This results in the error.

The Best Fixes for Scalar Variable Failure

There are severe fixes available to solve the issue and get your code running smoothly. Check the solutions below to choose the one that is best for you.

– Solving Undeclared Variable

This is easy: declare the @AuthorName variable before using it in the PRINT statement as below:

DECLARE @AuthorName VARCHAR(100) = ‘Vishal Balasubramanian’
PRINT @AuthorName

Output:

In the example above, we use the DECLARE statement (a requirement in SQL server) to declare the variable. The second step specifies the name of the variable. Remember that all local names start with @ as it is a syntax necessity. Lastly, we have defined the data type of the variable.

Note that if we do not make any initial value assigned to a variable, it is initialized as a NULL.

– Go Statement or Batch Separator Fix

You will need to redeclare the @AuthorName variable before using it in the PRINT statement after the GO statement, as shown below.

DECLARE @AuthorName VARCHAR(100) = ‘Vishal Balasubramanian’
PRINT @AuthorName
GO
DECLARE @AuthorName VARCHAR(100) = ‘Buscar’
PRINT @AuthorName

The output after executing the statement will be:

Vishal Balasubramanian
Buscar

Using the Go statement creates a new branch where the variables declared are not visible past the statement. So, all variables declared at the top of the file will not be accessible if the go statement is executed.

Although the variable @AuthorName is declared twice, the code still works. Here is why there is a batch separator, the Go statement, between the two variable declarations. The variable declared before the go statement is not accessed after the Go statement.

Typically, the SQL Server Management Studio ( SSMS) sends the first batch of statements to the SQL engine first for executions. It will send the second batch of statements after the Go statement to the SQL engine for execution when execution is over.

– Solving Local Declared Variable in Dynamic SQL Statement

Here is how to resolve the issue in the above statement:

DECLARE @AuthorName VARCHAR(100) = ‘Vishal Balasubramanian’
EXECUTE (‘PRINT ”’ + @AuthorName + ”” )

Output:

Alternatively, you can solve the above issue using the SP_EXECUTESQL statement, which allows parameterized statement. Check out this code for insights:

DECLARE @AuthorName VARCHAR(100) = ‘Vishal Balasubramanian’
EXECUTE SP_EXECUTESQL N’PRINT @AuthorName’,
N’@AuthorName VARCHAR(100)’,@AuthorName

The output after executing the program will be:

While executing a dynamic SQL, it is executed in a different scope. Therefore, if you declare your variables in the same scope as the VARCHAR variable with the SQL statement, you definitely will get that error.

But it is pretty impossible to access the variable from outside the dynamic SQL. You can resolve that issue in two ways:

  • Insert the code that uses the variable in the dynamic SQL
  • Insert the value in a temporary table (table will be seen outside the scope) and use it outside dynamic – execute SELECT against the temporary table.
  • Parameterize and do not inject raw string in a dynamically generated statemen. SQL injection is a huge problem, rendering it an incorrect way of doing it.

– Other Causes and Fixes of Undeclared Variable

You might also get an “Undeclared variable” error when declaring a variable but not assigning it. Check out this example:

SELECT idSubscriber
INTO newsletterToSend
FROM subscribers

When you execute the statement, it generates an error: #1327 – Undeclared variable: newsletterToSend.

The problem, in this case, is that SQL does not support SELECT INTO [table] syntax. Instead, it only supports SELECT INTO [variable], and you can declare each variable individually and assign a value for every parameter in case of multiple SQL variables.

To solve this issue, you will need to use the CREATE TABLE syntax with SELECT, as shown below:

CREATE TABLE bar ([column list]) SELECT * FROM foo;

The below query will work fine:

CREATE TABLE New_Table_name
SELECT * FROM Original_Table_name;

SQL allows you to use two methods to assign values to a variable:

  • SET statement
  • SELECT statement

To use set, declare a variable and then assign a value using the SET statement.

For example:

DECLARE @AuthorName VARCHAR(100)
SET @TestVariable = ‘Vishal Balasubramanian’
PRINT @AuthorName

The output after executing the statement is:

To use the SELECT statement, insert it in the place of the SET statement.

You can use the SELECT statement to assign a value to a variable from the table, view, or scalar-valued functions. Nevertheless, if not done well, the error: Must declare the scalar variable in select statement can occur.

Must Declare the Scalar Variable Stored Procedure

In SQL, stored procedures let you create and store SQL queries and later execute them on a server. Their primary purpose is to hide direct SQL queries from the code and improve the performance of database operations such as selecting, updating, and deleting data.

While using them, you may encounter errors such as must declare the scalar variable @date. When this error occurs, you must declare and initialize this variable first.

Conclusion

While creating SQL queries, errors are inevitable, even if you are very careful. You need to reread your code and learn a few tricks for solving mistakes. Here is the rundown of our article:

  • SQL requires that you declare statements using the DECLARE statement; you will get an error if you don’t.
  • Always start local names with @ because it is a syntax necessity. So, you declare a variable as DECLARE @Name.
  • A batch separator, the Go statement separates two statements ensuring that a variable declared before the go statement is not accessed after the Go statement.
  • Dynamic SQL is executed in a different scope. Therefore, if you declare your variables in the same scope as the VARCHAR variable with the SQL statement, you definitely will get that error.

Right way to declare a variable in sqlSince you know the possible causes and fixes, you can easily avoid the error or fix it soon as it pops up.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

MariaDB 10.3.14

I have a function that generates the root id in a hierarchy:

Hierarchy

The function is this:

CREATE FUNCTION `getRootId`(GivenID INT) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE ch INT;
DECLARE root INT;
SET ch = GivenID;

WHILE ch >= 0 DO
    SELECT id, parent_id INTO root, ch  FROM
    (SELECT id, parent_id FROM pctable WHERE id = ch) A;
END WHILE;
RETURN root;
END

I want to be able to provide the id, parent_id and table name as variables to this function, so i can easily be able to use it in different hierarchy tables easily.

something like this:

CREATE FUNCTION `getRootId`(GivenID INT,id_column_name varchar(45),parent_id_column_name varchar(45),target_table_name varchar(45))

One function to be used for both Topics, Indicators ….

enter image description here

I’m new to advanced SQL coding, so apologies if this is a newbie question.

Many thanks.

Updates:

I switched to procedure to use prepared statements:

CREATE DEFINER=`root`@`localhost` PROCEDURE `getRootIdFlex`(IN GivenID INT,IN id_name varchar(45),IN parent_name varchar(45),IN tbl_name varchar(45) , OUT root varchar(1000))
DETERMINISTIC
BEGIN
DECLARE id_or_parent INT;

SET @tbl_name = tbl_name;
SET @id_name = id_name;
SET @parent_name = parent_name;

SET id_or_parent = GivenID;

SET @s := CONCAT('SELECT ?, ? INTO root, id_or_parent FROM (SELECT ?, ? FROM ? WHERE ? = id_or_parent) A');
PREPARE stmt FROM @s;
WHILE id_or_parent >= 0 DO
    EXECUTE stmt USING @id_name, @parent_name, @id_name, @parent_name, @tbl_name, @id_name;
END WHILE;
END

But when i execute the procedure this way:

SET @root := NULL;
CALL getRootIdFlex(11, 'Topic_id', 'Topic_Topic_id','Topic', @root);
SELECT @root;

I get:

Error Code: 1327. Undeclared variable: root

The root is declared as OUT variable. Why this error ?

Понравилась статья? Поделить с друзьями:
  • Error code 11 1312 xerox b205
  • Error code 11 114
  • Error code 1318
  • Error code 11 1114 xerox
  • Error code 1305 sql