Published on

March 19, 2013

Passing SQL Server Stored Procedure Result as Parameter

Stored Procedures are widely used in SQL Server for their efficiency and reusability. One common requirement is to pass the result of one stored procedure as a parameter to another stored procedure. In this blog post, we will explore how to achieve this using a simple example.

Let’s start by creating two stored procedures. The first stored procedure, called SquareSP, calculates the square of a given parameter. Here is the code:

CREATE PROCEDURE SquareSP
@MyFirstParam INT
AS
DECLARE @MyFirstParamSquare INT
SELECT @MyFirstParamSquare = @MyFirstParam*@MyFirstParam
RETURN (@MyFirstParamSquare)
GO

The second stored procedure, called FindArea, calculates the area of a circle using the squared parameter passed from the first stored procedure. Here is the code:

CREATE PROCEDURE FindArea
@SquaredParam INT
AS
DECLARE @AreaofCircle FLOAT
SELECT @AreaofCircle = @SquaredParam * PI()
RETURN (@AreaofCircle)
GO

Now, let’s see how we can pass the result of the first stored procedure to the second stored procedure as a parameter. We can achieve this by following these steps:

  1. Declare variables to hold the result and final area:
  2. DECLARE @ParamtoPass INT, @CircleArea FLOAT
    
  3. Execute the first stored procedure and assign the result to the variable:
  4. EXEC @ParamtoPass = SquareSP 5
    
  5. Execute the second stored procedure and pass the variable as a parameter:
  6. EXEC @CircleArea = FindArea @ParamtoPass
    
  7. Finally, retrieve the final area:
  8. SELECT @CircleArea FinalArea
    

    By following these steps, we can easily pass the result of one stored procedure to another stored procedure.

    After executing the code, you can clean up by dropping the stored procedures:

    DROP PROCEDURE SquareSP
    DROP PROCEDURE FindArea
    GO
    

    I hope you found this blog post helpful in understanding how to pass the result of one stored procedure as a parameter to another stored procedure in SQL Server. If you have any questions or thoughts, please leave a comment below.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.