Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a variable in MySQL for a normal query?

How can I declare a variable for a normal query in MySQL?

e.g.,

declare @myVar date; set @myVar = something;  select * from someTable where someColumn = @myVar; 

I tried and the syntax seems to be wrong...what am I missing?

like image 923
EOB Avatar asked Jun 05 '12 07:06

EOB


People also ask

Can we declare variable in MySQL query?

You can declare a variable using @anyVariablename which is a session variable. To create a session variable, you need to use SET command.

How do you set a variable in MySQL query?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

How do you declare a variable in SQL query?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.


1 Answers

You can declare a session variable in this way :

SET @myvarname := 'value'; 

or a local variable in this way :

DECLARE my_variable varchar(30) 

also:

DECLARE my_variable varchar(30) DEFAULT 'value' 
like image 101
aleroot Avatar answered Oct 01 '22 12:10

aleroot