Akshat Kumar Jain
Akshat Kumar Jain

Reputation: 21

Getting ERROR 1064 (42000) while SIMPLY declaring a variable in SQL

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE @var as int set @var = 21
WHILE (@var > 0) ' at line 1

Code:

DECLARE @var as int
    SET @var = 20               
    WHILE (@var > 0 )                   -- Condition
    BEGIN                             -- Begin
        PRINT replicate('* ', @var)       -- Print
        SET @var = @var - 1               -- Set
    END   

Upvotes: 0

Views: 354

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562280

In MySQL, @var is not the same variable as var.

The @var form is a user-defined session variable. You can't declare this type of variable. It is created implicitly if you set it to a value. You can use it outside of stored routines. It has no fixed data type.

The var form must be declared with the DECLARE statement. You can use it only in a stored routine. It is a local variable within the routine you declare it. It must be declared with a data type.

Procedure parameters are similar to declared variables, in that they are local to the procedure, they must have a data type, and they don't have a @ symbol.

If you set @var = 20, that does NOT set the value of var, and vice versa. These are two different variables.

Upvotes: 1

Related Questions