Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a value from one stored procedure in another?

I have the following statement in a stored procedure:

DECLARE @Count INT
EXEC @Count = GetItemCount 123
SELECT @Count

Which calls another stored procedure with the following statement inside:

SELECT COUNT(Item) 
FROM tblItem 
WHERE ID = @ID

However when I test the call the EXEC outputs the value correctly but it is not assigned to the @Count parameter correctly.

I've seen examples or stored procedures used like this, including here but none had a parameter and a return value used (that I could find).

The ID parameter is passed into the second statement which returns a count value used by the first stored procedure - all the info I have read seems to indicate this should work - but it doesn't the @Count value is always zero, even when the GetItemCount returns always the correct value.

This is in Microsoft SQL Server 2008 if that helps.

like image 874
RoguePlanetoid Avatar asked Jun 08 '10 09:06

RoguePlanetoid


People also ask

How do I use one stored procedure in another?

Here is an example of how to call a stored procedure inside another stored procedure. This is also known as nested stored procedures in SQL Server. Step 1: Create two simple stored procedure to insert some data into two different tables. both accept four parameters to insert the data.

How do you pass a table variable from one stored procedure to another?

You will need to create a TABLE TYPE then Declare a parameter of that type and yes it will be a read-only param but then you can get data into another table variable or temp table inside your param and do whatever you want to do with it.

Can I call a stored procedure from another?

In releases earlier than SQL Server 2000, you can call one stored procedure from another and return a set of records by creating a temporary table into which the called stored procedure (B) can insert its results or by exploring the use of CURSOR variables.


2 Answers

In your stored procedure, are you either

a) Assigning the value of the count to an output parameter:

CREATE PROCEDURE GetItemCount
  @id INT,
  @count INT OUTPUT
AS
  SELECT @count = COUNT(Item) FROM tblItem WHERE ID = @id

called as:

DECLARE @count INT
EXEC GetItemCount 123, @count OUTPUT

or, b) Assigning the count value as the return value:

CREATE PROCEDURE GetItemCount
  @id INT
AS
BEGIN
  DECLARE @count INT
  SELECT @count = COUNT(Item) FROM tblItem WHERE ID = @id

  RETURN @count
END  

called as:

DECLARE @count INT
EXEC @count = GetItemCount 123
like image 171
Matthew Abbott Avatar answered Sep 18 '22 23:09

Matthew Abbott


Another way

DECLARE @Count table(counting INT)
Insert into @Count
EXEC GetItemCount 123 
SELECT Counting FROM @Count 
like image 30
Madhivanan Avatar answered Sep 19 '22 23:09

Madhivanan