pysaundary
pysaundary

Reputation: 306

Fail to declare variable in mysql

This is the error I got when I try to run the query shown below:

Error Code: 1064. 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 productCount INT DEFAULT 0' at line 1

I am using Mysql workbench on ubuntu

enter image description here

Upvotes: 1

Views: 784

Answers (3)

IgorM
IgorM

Reputation: 1356

You can use DECLARE only in stored procedures. Here is a simple example of passing two variables to a stored procedure and declaring one variable inside the stored procedure

CREATE DEFINER=`myslq_user`@`%` PROCEDURE `createRecord`(IN _name NVARCHAR(255), IN _userID int)
BEGIN
    DECLARE val INT DEFAULT 0;
        INSERT INTO tbldata (Name, UserID, Value) VALUES (_name, _userID, val);
    END IF;
END

Upvotes: 1

nbk
nbk

Reputation: 49375

DECLARE only can be used in triggers,functions and stored procedures betewenn BEGIN and END see mysql maual

If you want to use a variable declare a user defined variable like @msg

use testdb;
SET @msg := 'testme if you can';
SET @testcount := 0;

SELECT @msg,@testcount + 1;

Result:

# @msg, @testcount + 1
testme if you can, 1

Upvotes: 3

slaakso
slaakso

Reputation: 9050

You can declare variables only inside routines.

Upvotes: 1

Related Questions