Tuesday, March 20, 2012

[SS2K5] : Populate a CTE from stored procedure result set

Hi,

I'd like to know if it's possible to populate/load a CTE from a stored procedure result set ?

Kind of :

USE MyDB;
GO
WITH MyCTE (Col1, Col2, Col3)
AS
(

EXECUTE myStoredProc

)
SELECT *
FROM MyCTE
GO

Thanks for your help.

Cheers,

Bertrand

A couple of options include loading your stored procedure output to a temp table:

INSERT NTO #aTempTable
EXEC yourStoredProcedure

and also converting your procedure into an function or perhaps a view and then you can join to the function or view. If the primary objective of the stored procedure is to be used as you describe it might be best from the outset to consider converting it into a function.

But also keep in mind that in many cases the temp table / stored procedure option will outperform the function.

|||

CTE in SQL Server 2005 is just syntactic sugar. It is similar to view in that the query expression of the CTE is parsed into the original query, compiled, optimized and executed. So there is no special optimization in terms of storing intermediate results in case of multiple references to the same CTE and so on. So you have few options:

1. Convert the SP to inline TVF - best performance

2. Convert the SP logic to a view

3. Convert the SP to non-inline TVF

4. Use a temporary table to store results from SP and reuse it

|||

Well in fact I have to perform a row by row operation on the sp result set. Which means using a cursor. And I know that using a cursor with a temporay table is not the best in term of performance so I thought that CTE was the best option...

But your first option could fits for my problem.

Thanks for your guidance.

|||What kind of row by row operation are you performing?|||

Well in fact I received a result set from one stored procedure. Each column in this result set become input parameters for an other stored proc I have to call.

It could be more "easy" if I had the right to modifiy the both of these stored proc but I'm not allowed to and I just can to plug my logic between these sp ....

No comments:

Post a Comment