0

I have two queries in the current page. They are very similar but still returning different number of records. Here is example:

Query 1

SELECT 
   recid,
   cost,
   cur_year
FROM Info i
   INNER JOIN Extension ex
       ON ex.recid = i.recid
       AND ex.categoryid = i.categoryid
WHERE cur_year = 2018
    AND info_id = 4531

Query 2

SELECT SUM(cost) AS cost_total
FROM Info i
   INNER JOIN Extension ex
       ON ex.recid = i.recid
       AND ex.categoryid = i.categoryid
WHERE cur_year = 2018
    AND info_id = 4531
    AND cost > 0

Query 1 in this case returns 2 records. Query 2 returns 1 record. I'm wondering if putting these two in SP would be a good idea? Current code has two separate queries and automatically hitting the database twice. My idea is two have one call to database and return two data sets. If anyone have example how this can be achieved please let me know. Thank you.

espresso_coffee
  • 5,980
  • 11
  • 83
  • 193

2 Answers2

0

Why not just include another column? Two queries in a stored procedure is still hitting the database twice.

And, you can express this as:

SELECT recid, cost, cur_date,
       SUM(CASE WHEN cost > 0 THEN cost ELSE 0 END) OVER () as total_cost
FROM Info i INNER JOIN
     Extension ex
     ON ex.recid = i.recid AND
        ex.categoryid = i.categoryid
WHERE cur_date = '2018' AND  -- this is suspicious.  Dates are not years
      info_id = '4531';
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

As some callers initiate return at first result set delivered, set nocount on at the beginning of your proc body. I know of no ways to have one query return 2 sets.

set nocount on;
JBJ
  • 393
  • 3
  • 8