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

落爺英雄遲暮 提交于 2019-12-05 01:39:30

问题


I'm trying to get a output parameter from MySQL stored procedure, let's have look a 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 won't return any value for me:

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 that how could I get the return value of the output parameter @id?


回答1:


I found a way to get the output parameter, to 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 your 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?



回答2:


MySQL doesnt work like SQL Server. If you want a store procedure with a return value, that you really want it's a function (UDF). You need specify the RETURN like any C++ function. Also you dont need use call, because its a function. Just use SELECT function()

Try to look up info about UDF in MySQL manual. There is very explicity help for do that.



来源:https://stackoverflow.com/questions/7480579/how-to-get-output-parameters-from-mysql-stored-procedure-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!