0

I tried setting a variable in sql as follows:

DECLARE @fromDate VARCHAR(60);
SET @fromDate = '2013-01-01 00:00:00';
SET @toDate = '2013-02-01 00:00:00';

SELECT @fromDate;

but this is not working.

what am I doing incorrectly?

1
  • SET @fromDate := '2013-01-01 00:00:00'; You are missing : Commented Oct 13, 2014 at 20:58

3 Answers 3

2

You don't DECLARE variables that start with @.

MySQL has two different types of variables. One is a session variable, with the @ prefix. The other type is the local variable inside a trigger or stored proc.

Sign up to request clarification or add additional context in comments.

Comments

1

The DECLARE statement is valid only inside of body of stored procedure or function, and this variables don't start by @.

The variables that start with @ don't need DECLARE, just use outside of stored procedure inclusive.

Comments

0

First lets take a look at how can we define a variable in mysql

To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

Using keyword 'SET'. Example :- mysql > SET @a = 1;

Without using keyword 'SET' and using ':='. Example:- mysql > @a:=1;

By using 'SELECT' statement. Example:- mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-

mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

@a := (select emp_name from employee where emp_id = 1); select emp_name into @a from employee where emp_id = 1; Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.

refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.