简体   繁体   中英

Error while invoking MySQL Stored procedure(that returns resultset) from Rails 3

I am invoking a stored procedure (MySQL) from my model. This stored procedure returns a resultset, but i get this error...

Mysql2::Error: PROCEDURE my_db.sp_venue_nearby_with_questions can't return a result set in the given context:....

Here's the rails code i use -

connection.select_all("call sp_some_proc()")

I have tried "connection.execute" as well, that fails as well. I have successfully been able to invoke another stored proc from my model, but that one does not return a resultset.

I tried the same thing with the MySQL 2 gem which is used by default in Rails 3 and got a similar error. The problem is that the MySQL 2 gem by default does not use the MULTI_STATEMENTS which is needed when you want to get a result set back from the procedure.

After some investigation I've decided to stick with the original MySQL gem ( adapter:mysql instead of adapter:mysql2 in database.yml ) which seems to work fine also in Rails 3.

Here is what I do in order to get the result from a stored procedure to an ActiveRecord class:

db = ActiveRecord::Base.connection.raw_connection
entries = Entry.find_by_sql( 'CALL sp_get_all_entries()' )

# we need to flush the result set otherwise following SQL statements cannot be processed
db.next_result if ( db.more_results? )

Now the rows returned from the stored procedure will be available on the entries objects, eg

entries.each do |entry|
    puts entry.name
    puts entry.extra_column_from_sp
end

Note that you can add extra columns in the SP. Those extra columns will always be of type "String" so you might need to convert them, eg to a date.

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