tags:

views:

178

answers:

4

When would you use an output parameter vs a return variable, or vice versa? In the following simple example, I can achieve the same thing using either one.

Using output parameter

create proc dbo.TestOutput (@InValue int, @OutValue int output)
as
set @OutValue = @InValue

declare @x int
exec TestOutput @InValue = 3, @OutValue = @x output
select @x 

Using return variable:

create proc dbo.TestReturn (@InValue int)
as
return @InValue

declare @x int
exec @x = TestReturn @InValue = 3
select @x 

As you can see, they both do the same thing. Can someone show me an example where the choice of a output parameter vs a return variable would make a difference?

+4  A: 

I prefer:

Using a return value when you only need to return one item.

Using output parameters when you need to return more than one value.

Another common usage pattern is to use return values only to inform of success or failure and output parameters for anything that needs to be returned.

klabranche
I liked this answer better before you edited it. Now it reads like "Many do this...but you could do this instead". You may wanna pick one :P
cHao
Just laying out the two main streams of thought on it. :-)
klabranche
+4  A: 

This is T-SQL, not C. Never use return values, many client side APIs make dealing with return values a pain if not plain impossible. Always use OUTPUT parameters.

Remus Rusanu
RETURN values indicating success/failure can be very useful when dealing with nested stored procedure calls.
Philip Kelley
I would say that BEGIN TRY/BEGIN CATCH and RAISERROR are way more useful than return values.
Remus Rusanu
+2  A: 

Since return values only work with int, it ends up being "inconsistent". I prefer the output param for consistency.

Also, output params force the caller to recognize the returned value. IME, return values are routinely ignored.

Mark Brackett
A: 

You should use RETURN to return a value from a procedure much in the same way you'd use EXIT to return a value in a batch script. Return isn't really for parameter passing, but rather as a way to quit out of a procedure or query. As per MSDN documentation:

Unless documented otherwise, all system stored procedures return a value of 0. This indicates success and a nonzero value indicates failure.

This becomes more evident once you recognize the lack of any ability to define a type to your return value. It has to be INT.

Jeff Wight