How to get output parameters from MySQL stored procedure in Rails?

I am trying to get the output parameter from a MySQL stored procedure, let's see an example below:

1 In mysql, I created this procedure and it works.

CREATE PROCEDURE sp_name (out id int)
Begin
    select id into @id from table order by id desc limit 1;
End

mysql> call sp_deduct_credit_and_money(@id);
Query OK, 0 rows affected (0.01 sec)

mysql> select @id;
+--------------+
|          @id |
+--------------+
|           24 |
+--------------+
1 row in set (0.00 sec)

2 Therefore, it also works in Rails, but it will not return me any value:

ActiveRecord::Base.connection.execute("call sp_name(@id)")
ActiveRecord::Base.connection.execute("select @id")

Here is the log in Rails

(2.0ms)  call sp_name(@id)
(0.1ms)  select @id

My question is, how can I get the return value of the output parameter @id?

+5
source share
2 answers

I found a way to get the output parameter, share with you guys, see below:

1 to create a connection

client = Mysql2::Client.new(ActiveRecord::Base.configurations[Rails.env.to_s].symbolize_keys)

2 use this connection to call sp

client.query "call sp_xxx"

3 to get the output parameter

result = client.query("select @output_parameter")

4 return the output

return !result.first["@output_parameter"].nil?
+3

MySQL , SQL Server. , , (UDF). RETURN, ++. , . SELECT()

UDF MySQL. .

0

All Articles