Search code examples
sqlsql-serversql-server-2008coldfusionqoq

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


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?


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