简体   繁体   中英

Combine results from multiple stored procedures

I have 3 stored procedures (spData1, spData2, spData3) that query regional summary results from two tables (tSites, tInspections) linked by a SiteID key. I cannot combine the queries due to differing join methods and GROUP BY requirements of the required summary information. Each stored procedure takes a @Year (smallint) parameter for the year in which they want the summary information. And to makes things really fun, the procedures don't always return the same number of records, depending on the year.

  1. spData1 returns RegionName, TotalSitesVisited, and TotalViolations
  2. spData2 returns RegionName and TotalSiteVisits
  3. spData3 returns RegionName and TotalBadSites

How do I create a fourth stored procedure to return all of this information in one result:

spData4 returns RegionName, TotalSitesVisited, TotalViolations, TotalSiteVisits, TotalBadSites

Thanks!

At the beginning of your procedure (spData4) create three temp tables that corespond to the output columns of three stored procedures.

Run all 3 sps using INSERT..EXEC and insert data into 3 temp tables.

At the end write a query that JOIN the result of 3 temp tables and return it as SELECT from procedure

Something like this (fix for your correct column types):

CREATE PROCEDURE spData4 (@Year smallint)
AS
BEGIN

 CREATE TABLE #temp1 (RegionName NVARCHAR(50), TotalSitesVisited INT, TotalViolations INT)
 CREATE TABLE #temp2 (RegionName NVARCHAR(50), TotalSiteVisits INT)
 CREATE TABLE #temp3 (RegionName NVARCHAR(50), TotalBadSites INT)

 INSERT INTO #temp1 EXEC spData1 @Year
 INSERT INTO #temp2 EXEC spData2 @Year
 INSERT INTO #temp3 EXEC spData3 @Year

 SELECT 
  COALESCE(t1.RegionName, t2.RegionName, t3.RegionName) RegionName
  ,TotalSitesVisited,TotalViolations,TotalSiteVisits,TotalBadSites 
 FROM #temp1 t1
 FULL JOIN #temp2 t2 ON t1.RegionName = t2.RegionName 
 FULL JOIN #temp3 t3 ON t1.RegionName = t3.RegionName OR t2.RegionName = t3.RegionName

END 

Alternatively, if you don't need old SPs anymore, you can copy your code from all three SPs here and have it as three separate parts that each fill it's own #temp table. Join at the end the same way.

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