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.
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.
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.
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.
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
Another way
DECLARE @Count table(counting INT)
Insert into @Count
EXEC GetItemCount 123
SELECT Counting FROM @Count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With