What I'm trying to do is to have an optional parameter in my stored procedure that gets the default value defined in the table if not provided.
create table primates (
id int identity(1,1) primary key,
genus varchar(32) not null default 'gorilla'
);
go
create procedure spawn_primate
@genus varchar(32) = default
as begin
set nocount on;
insert into primates
(genus)
values
(@genus);
end;
go
exec spawn_primate
-- Cannot insert the value NULL into column 'genus', table 'my_db.dbo.primates'; column does not allow nulls. INSERT fails.
In the code above, I want @genus to be equal to gorilla if not provided, but SQL Server treats it as NULL. Well, I can set the default value to be the one I used in the table like so: @genus varchar(32) = 'gorilla', but then I have to keep an eye on my default values and make sure they are the same everywhere, which is a bit of a hassle...
Is there a (preferably clean) way to do this? Maybe I can check if @genus is NULL and get the default value from underlying system tables and set it, but am not sure if it's the best way.
By the way, what's the difference between = NULL and = default?