How to use one result set to generate multiple manipulated result sets from that without hitting the db multiple times?

StackOverflow https://stackoverflow.com/questions/23193023

Question

I am designing a report using ColdFusion and SQL. The reprot is having 3 section. Now all the 3 sections are using the same set of data but manipulate it differently to show different results. I have used CTE for this. I have written 3 quires for the 3 sections.

WITH allOrders AS(  
Main query[With a lot of Joins]
)
SELECT  [Manupulated_Resultset_1]
FROM    allOrders 

WITH allOrders AS(  
Main query[With a lot of Joins]
)
SELECT  [Manupulated_Resultset_2]
FROM    allOrders 

WITH allOrders AS(  
Main query[With a lot of Joins]
)
SELECT  [Manupulated_Resultset_3]
FROM    allOrders 

So for the three sections it is hitting to the database 3 times where as for all the cases the main query remains the same only the child query changes. I know this can be done in a much better way. So I need a way to store the main query results once and then use that to get the different manipulated results.

I can not use query of query in ColdFusion as to get the manipulated result sets it involves a lot of operation that QOQ does not support.

So is there any way in SQL to this?

Was it helpful?

Solution

Create a stored procedure, use a temp table to store the result of main query and then return multiple resultsets to the client in one go:

create procedure proc_name
as
set nocount on
;with allOrders as (  
Main query[With a lot of Joins]
)
select *
into #allOrders
from allOrders;

SELECT  [Manupulated_Resultset_1]
FROM    #allOrders;
SELECT  [Manupulated_Resultset_2]
FROM    #allOrders;
SELECT  [Manupulated_Resultset_3]
FROM    #allOrders;

GO

http://www.adobe.com/devnet/coldfusion/articles/stored_procs.html

OTHER TIPS

use a query of queries or create a DB view that joins the necessary tables so you can distribute some of the resources used to db side. best practice is the stored procedure

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top