Wednesday, May 29, 2013

SQL SERVER – Pass One Stored Procedure’s Result as Another Stored Procedure’s Parameter

This is one of the most asked questions in recent time and the answer is even simpler.
Here is the question – How to Pass One Stored Procedure’s Result as Another Stored Procedure’s Parameter. Stored Procedures are very old concepts and every day I see more and more adoption to Stored Procedure over dynamic code. When we have almost all of our code in Stored Procedure it is very common requirement that we have need of one stored procedure’s result to be passed as another stored procedure’s parameter.
Let us try to understand this with a simple example. Please note that this is a simple example, the matter of the fact, we can do the task of these two stored procedure in a single SP but our goal of this blog post is to understand how we can pass the result of one SP to another SP as a parameter.
Let us first create one Stored Procedure which gives us square of the passed parameter.
-- First Stored ProcedureCREATE PROCEDURE SquareSP@MyFirstParam INT
AS
DECLARE 
@MyFirstParamSquare INT
SELECT 
@MyFirstParamSquare @MyFirstParam*@MyFirstParam-- Additional CodeRETURN (@MyFirstParamSquare)GO
Now let us create second Stored Procedure which gives us area of the circle.
-- Second Stored ProcedureCREATE PROCEDURE FindArea@SquaredParam INT
AS
DECLARE 
@AreaofCircle FLOAT
SELECT 
@AreaofCircle @SquaredParam PI()RETURN (@AreaofCircle)GO
You can clearly see that we need to pass the result of the first stored procedure (SquareSP) to second stored procedure (FindArea). We can do that by using following method:
-- Pass One Stored Procedure's Result as Another Stored Procedure's ParameterDECLARE @ParamtoPass INT@CircleArea FLOAT-- First SPEXEC @ParamtoPass SquareSP 5-- Second SPEXEC @CircleArea FindArea @ParamtoPassSELECT @CircleArea FinalArea
GO
You can see that it is extremely simple to pass the result of the first stored procedure to second procedure.
You can clean up the code by running the following code.
-- Clean upDROP PROCEDURE SquareSPDROP PROCEDURE FindArea
GO

No comments:

Post a Comment