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.
CREATE PROCEDURE GetImmediateManager
@employeeID INT,
@managerID INT OUTPUT
AS
BEGIN
SELECT @managerID = ManagerID
FROM HumanResources.Employee
WHERE EmployeeID = @employeeID
if @@rowcount = 0 -- manager not found?
return 1;
END
And you call it this way:
DECLARE @return_status int;
DECLARE @managerID int;
EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
print N'Immediate manager not found!';
else
print N'ManagerID is ' + @managerID;
go
You should use the return value for status codes only. To return data, you should use output parameters.
If you want to return a dataset, then use an output parameter of type cursor.
CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT
AS
Begin
DECLARE @cnt int;
DECLARE @status int =0;
SET NOCOUNT OFF
SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
if(@cnt = 1)
Begin
return @status;
End
else
Begin
SET @status =1;
return @status;
End
END
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)
To this:
declare @t table(id int)
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)