mysqlsqlstored-procedures

How can I select out parameters in a MySQL procedure as table columns?


Environment: MySQL 5.1, Linux

I have a stored procedure that computes several values from a single input value. The values are returned as OUT parameters. I would like to call this procedure for every row set and have the values appear as columns in the result set. The values have a complex relationship such that distinct functions for each value is not easily constructed.

The question: How can I get OUT parameters to show up as columns in a table?

Here's what I have so far:

DELIMITER $_$
DROP PROCEDURE IF EXISTS in_out;
CREATE PROCEDURE in_out (
       IN s TEXT, 
       OUT op TEXT, 
       OUT opn INT,
       OUT opd TEXT,
       OUT len INT
       )
BEGIN
        SET op = 'del';
        SET opn = 1;
        SET opd = substr(s,4);
        SET len = LENGTH(SUBSTR(s,4));
END
$_$
DELIMITER ;

Then:

mysql> call in_out('delACT',@op,@opn,@opd,@len);
Query OK, 0 rows affected (0.00 sec)

mysql> select @op,@opn,@opd,@len;
+------+------+------+------+
| @op  | @opn | @opd | @len |
+------+------+------+------+
| snv  |    1 | ACT  |    3 |
+------+------+------+------+
1 row in set (0.00 sec)

So far so good, but I can't figure out how to call this procedure for every row and return the results in the result set. I want is something like this:

dream> select mycol,in_out(mycol) from mytable
+---------+------+------+------+------+
| mycol   | @op  | @opn | @opd | @len |
+---------+------+------+------+------+
| delACT  | del  |    1 | ACT  |    3 |
+---------+------+------+------+------+

Thanks!


Solution

  • This appears to be a trick question: one can't create table relations out of function/procedure results in MySQL. I ended up refactoring into separate functions (as suggested by Michał). I had been hoping for a MySQL equivalent to PostgreSQL's table functions (http://www.postgresql.org/docs/9.1/static/queries-table-expressions.html#QUERIES-TABLEFUNCTIONS).