Sproc may return multiple data sets - how to best capture only the first data set when it's unknown whether there will be more than one?

16 views
Skip to first unread message

Tim Tilberg

unread,
May 6, 2016, 1:12:31 PM5/6/16
to Rails SQLServer Adapter
I have a series of sprocs in my db that typically return more than one result set. Only the first result set is the data I'm interested for a Ruby class I'm working on. The additional result sets are more for me to summarize the above data to make sure it's reasonable before sending it to clients. There are a few however that only return one single result set.

The example in the readme was interesting:
set1, set2 = results.each
set1 # => [ set1_record1, set1_record2, set1_record3 ]
set2 # => [ set2_record1, set2_record2, set2_record3 ]

This seems to operate off of results.each returning an array instead of enumerator, and then using Ruby's built in tricks to unpack and assign.

However, if I try the same thing with a query that only returns a single result set, I end up with
set1, set2 = results.each
set1 # => [ set1_record1 ]
set2 # => [ set1_record2 ]


The next closest thing I could think of was calling .each twice, and on the second call sending it a block to stop the results from proceeding.


Ultimately I'm trying to create a simple utility method I can reuse that looks something like:

  def sproc_to_csv
    results
= @db.execute "EXEC tire_pricing_mapping.dbo.#{report_sproc}"
    CSV
.generate do |csv|
      csv
<< results.fields
      results
.each do |row|
        csv
<< row.values
     
end
   
end
 
end


But is also able to be compatible with sprocs that both return single and multiple result sets, only using the first.


Is this something anyone can provide guidance towards?

Thank you.

Reply all
Reply to author
Forward
0 new messages