views:

56

answers:

1

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

Mysql2::Error: PROCEDURE loqly.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.

A: 

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, e.g.

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, e.g. to a date.

Wolfgang