Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store a value from a SELECT statement in a variable in a MySQL Stored Procedure?

People also ask

How can we store value of SELECT query in a variable in MySQL?

There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.

How do you store a value in a variable in SQL query?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Can we store value in variable in MySQL?

You can store a value in a user-defined variable in one statement and refer to it later in another statement. This enables you to pass values from one statement to another. User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ .

WHERE is the data from a SELECT statement stored?

The SQL SELECT Statement The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.


In a stored procedure do this:

SELECT COUNT(barcode) AS count into @myVar FROM movieitems;

SELECT @someVariable := COUNT(barcode) FROM movie ...

You can then use @someVariable in other queries. E.g.

SELECT * FROM some_table WHERE some_field > @someVariable;

And you can also manipulate the variable using SET:

SET @someVariable = @someVariable + 1;