Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql set multiple variables from one select

Tags:

I'm starting to pull my hair out here is something like this even possible?

DECLARE var1 int; DECLARE var2 int; DECLARE var3 int; SELECT var1:=id, var2:=foo, var3:=bar from page WHERE name="bob"; CALL someAwesomeSP (var1 , var2 , var3 ); 

The above doesn't work but i am trying to figure out how I would accomplish this. My ultimate goal here is to call a select and than call stored proc with data from select.
Thanks

like image 629
MrB Avatar asked Jul 02 '13 04:07

MrB


People also ask

How do I declare multiple variables in MySQL?

DECLARE var1 int; DECLARE var2 int; DECLARE var3 int; SELECT var1:=id, var2:=foo, var3:=bar from page WHERE name="bob"; CALL someAwesomeSP (var1 , var2 , var3 );

What is @@ in MySQL?

@@ - System Variable @@ is used for system variables. Using different suffix with @@ , you can get either session or global value of the system variable.

How do you assign results of a query to a variable in MySQL?

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 I change global variables in MySQL?

The following discussion describes the syntax options for setting system variables: To assign a value to a global system variable, precede the variable name by the GLOBAL keyword or the @@GLOBAL. qualifier: SET GLOBAL max_connections = 1000; SET @@GLOBAL.


2 Answers

This worked for me.

        DECLARE var1 int;         DECLARE var2 int;         DECLARE var3 int;         SELECT id, foo, bar INTO var1, var2, var3 from page WHERE name="bob";         CALL someAwesomeSP (var1 , var2 , var3 ); 

Thanks to Zec. The first link helped me understand the correct syntax or at least what is working for me.

like image 94
MrB Avatar answered Nov 08 '22 15:11

MrB


For MySQL, please take a look this example code:

-- Init variables SET @var1 = 0; SET @var2 = 0; SET @var3 = 0; SELECT VALUE1, VALUE2, VALUE3 INTO @var1, @var2, @var3 FROM COOL_TABLE WHERE VALUE_ID = 12345;  -- Then you can use declared variables SELECT * FROM ANOTHER_TABLE WHERE VALUE1 = @var1 AND VALUE2 = @var2 
like image 34
KimchiMan Avatar answered Nov 08 '22 15:11

KimchiMan