简体   繁体   中英

MySQL: Use a select statement for stored procedure parameter

I have a stored procedure that works:

call my_procedure('A,B,C,D');

I want to populate the A,B,C with a list from a subquery of another table, eg:

call my_procedure(
  SELECT group_concat(letters) FROM table WHERE type = 'some_type')
);

Possible? Or am I doing it wrong?

SELECT my_function(group_concat(letters)) FROM table WHERE type = 'some_type';

You can assign the value to a user-defined variable and then pass that variable to the function.

For example:

SELECT group_concat(letters) 
INTO @foo
FROM table 
WHERE type = 'some_type';

call my_function(@foo);

Yes, you can pass a string to a procedure that's returned as the result of subquery.

But not as a bare query:

mysql> create procedure foo (in s text) begin select s; end !!

mysql> call foo( select group_concat(user) from mysql.user );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 
'select group_concat(user) from mysql.user )' at line 1

If you enclose the query in parentheses, it counts as a scalar subquery , that is, a subquery that is bound to return one row, one column:

mysql> call foo( (select group_concat(user) from mysql.user) );
+--------------------+
| s                  |
+--------------------+
| root,root,bill,xbm |
+--------------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM