Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize output parameters in stored procedure

I have a stored procedure with an output parameter that I initialize with "0":

ALTER PROCEDURE dbo.SomeProcedure
    @someparam INT = 0 OUT
...

However, when the procedure does not modify or set that parameter during execution, the output value is NULL, not "0" as expected.

Is it mandatory to set the default value in the procedure code

SET @someparam = 0; 

and avoid the initialization in declaration?

Why SQL Server allows default values in declaration for output parameters then?

like image 473
net_prog Avatar asked Dec 26 '22 14:12

net_prog


1 Answers

The syntax you show is not for initialization, is for default values for missing parameters:

default A default value for a parameter. If a default value is defined for a parameter, the procedure can be executed without specifying a value for that parameter.

So then it should be clear that if you can read the output value, it must be the case that you are providing a parameter for @someparam and therefore it is not 'missing'. If is not 'missing', then it is not assigned a default value because it must already have a value, the one from your caller frame (probably NULL). QED.

The following code shows the difference and exemplifies the behavior you see:

create procedure usp_test
    @p int = 0 output
as
    set @p += 1;
    select @p;
go

exec usp_test;
go


declare @unitialized int;
exec usp_test @unitialized output;
go
like image 124
Remus Rusanu Avatar answered Jan 11 '23 17:01

Remus Rusanu