Helo,
My question is I have one Stored Procedure in SQL Server that returns counts of a field. I want to store the results of this Stored Procedure in a variable (scalar?) of a different stored procedure.
sp_My_Other_SP:
CREATE PROCEDURE [dbo].sp_My_Other_SP
@variable int OUTPUT -- The returned count
AS
BEGIN -- SP
SET NOCOUNT ON;
SET @SQL = "SELECT COUNT(*) FROM blah"
EXEC(@SQL)
END -- SP
I currently do it like:
DECLARE @count int
EXEC sp_My_Other_SP @count OUTPUT
Then I use it like
IF (@count > 0)
BEGIN
...
END
However its returning the other Stored Procedure results as well as the main Stored Procedure results which is a problem in my .NET application.
-----------
NoColName
-----------
14
-----------
MyCol
-----------
abc
cde
efg
(Above is an attempted representation of the results sets returned)
I would like to know if there is a way to store the results of a Stored Procedure into a variable that doesn't also output it.
Thanks for any help.
You can use one or more RETURN statements in a stored procedure. The RETURN statement can be used anywhere after the declaration blocks within the SQL-procedure-body. To return multiple output values, parameters can be used instead. Parameter values must be set prior to the RETURN statement being executed.
Stored procedures do not have a return value but can take a list with input, output, and input-output parameters.
You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success. If no return is explicitly set, then the stored procedure returns zero.
In order to fetch the multiple returned values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword. You can also make use of the Split function to split the comma separated (delimited) values into rows.
You can capture the results of the stored procedure into a temp table so it is not returned by the calling stored procedure.
create table #temp (id int, val varchar(100))
insert into #temp
exec sp_My_Other_SP @value, @value, @value, @count OUTPUT
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