Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MySQL variables in a query

Tags:

mysql

I am trying to use this MySQL query:

SET @a:=0; UPDATE tbl SET sortId=@a:=@a+1 ORDER BY sortId;

Unfortunately I get this error:
"Parameter '@a' must be defined"

Is it possible to batch commands into 1 query like this, or do I need to create a stored procedure for this?

like image 913
Jon Tackabury Avatar asked Mar 31 '10 20:03

Jon Tackabury


People also ask

Can I use variables 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.

How do I use variables in MySQL?

MySQL variable assignment 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 I assign a SQL query result to a variable?

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 you have variables in MySQL?

The MySQL server maintains system variables that configure its operation. A system variable can have a global value that affects server operation as a whole, a session value that affects the current session, or both.


2 Answers

You placed the variable assignment in a wrong place:

SET @a:=0; UPDATE tbl SET @a:=sortId=@a+1 ORDER BY sortId;
like image 159
newtover Avatar answered Sep 25 '22 19:09

newtover


I think you need a stored procedure for any kind of statefullness. Is there a reason you have been reluctant to create one?

Also how are you running this code? Is it in an editor like SQL Server Manager or as a string in a program?

like image 26
Joshua Jewell Avatar answered Sep 26 '22 19:09

Joshua Jewell