Output parameters and default values do not work well together! This is from SQL 10.50.1617 (2008 R2). Do not be fooled into believing this construct magically does a SET
to that value on your behalf (like my co-worker did)!
This "toy" SP interrogates the OUTPUT
parameter value, whether it is the default value or NULL
.
CREATE PROCEDURE [dbo].[omgwtf] (@Qty INT, @QtyRetrieved INT = 0 OUTPUT)
AS
IF @QtyRetrieved = 0
BEGIN
print 'yay its zero'
END
IF @QtyRetrieved is null
BEGIN
print 'wtf its NULL'
END
RETURN
If you send in an uninitialized value (i.e. NULL
) for the OUTPUT
, you really got NULL
inside the SP, and not 0
. Makes sense, something got passed for that parameter.
declare @QR int
exec [dbo].[omgwtf] 1, @QR output
print '@QR=' + coalesce(convert(varchar, @QR),'NULL')
output is:
wtf its NULL
@QR=NULL
If we add an explicit SET
from the caller we get:
declare @QR int
set @QR = 999
exec [dbo].[omgwtf] 1, @QR output
print '@QR=' + coalesce(convert(varchar, @QR),'NULL')
and the (unsurprising) output:
@QR=999
Again, makes sense, a parameter is passed, and SP took no explicit action to SET
a value.
Add a SET
of the OUTPUT
parameter in the SP (like you're supposed to do), but do not set anything from the caller:
ALTER PROCEDURE [dbo].[omgwtf] (@Qty INT, @QtyRetrieved INT = 0 OUTPUT)
AS
IF @QtyRetrieved = 0
BEGIN
print 'yay its zero'
END
IF @QtyRetrieved is null
BEGIN
print 'wtf its NULL'
END
SET @QtyRetrieved = @Qty
RETURN
Now when executed:
declare @QR int
exec [dbo].[omgwtf] 1234, @QR output
print '@QR=' + coalesce(convert(varchar, @QR),'NULL')
the output is:
wtf its NULL
@QR=1234
This is the "standard" behavior for OUTPUT
parameter handling in SPs.
Now for the plot twist: The only way to get the default value to "activate", is to not pass the OUTPUT
parameter at all, which IMHO makes little sense: since it's set up as an OUTPUT
parameter, that would mean returning something "important" that should be collected.
declare @QR int
exec [dbo].[omgwtf] 1
print '@QR=' + coalesce(convert(varchar, @QR),'NULL')
gives this output:
yay its zero
@QR=NULL
But this fails to capture the SPs output, presumably the purpose of that SP to begin with.
IMHO this feature combination is a dubious construct I would consider a code smell (phew!!)
NULL
in whatever you pass for@AddressId
when an address doesn't exist, without using a branch?" – ruffin