Christophe,
The default value on a column is only applied if you don't specify the column in the INSERT statement.
Since you're explicitiy listing the column in your insert statement, and explicity setting it to NULL, that's overriding the default value for that column
What you need to do is "if a null is passed into your sproc then don't attempt to insert for that column".
This is a quick and nasty example of how to do that with some dynamic sql.
Create a table with some columns with default values...
create table myTable (
always varchar(50),
value1 varchar(50) default ('defaultcol1'),
value2 varchar(50) default ('defaultcol2'),
value3 varchar(50) default ('defaultcol3')
)
Create a SPROC that dynamically builds and executes your insert statement based on input params
alter procedure t_insert (
@always varchar(50),
@value1 varchar(50) = null,
@value2 varchar(50) = null,
@value3 varchar(50) = null
)
as
begin
declare @insertpart varchar(500)
declare @valuepart varchar(500)
set @insertpart = 'INSERT INTO myTable ('
set @valuepart = 'VALUES ('
if @value1 is not null
begin
set @insertpart = @insertpart + 'value1,'
set @valuepart = @valuepart + '''' + @value1 + ''', '
end
if @value2 is not null
begin
set @insertpart = @insertpart + 'value2,'
set @valuepart = @valuepart + '''' + @value2 + ''', '
end
if @value3 is not null
begin
set @insertpart = @insertpart + 'value3,'
set @valuepart = @valuepart + '''' + @value3 + ''', '
end
set @insertpart = @insertpart + 'always) '
set @valuepart = @valuepart + + '''' + @always + ''')'
--print @insertpart + @valuepart
exec (@insertpart + @valuepart)
end
The following 2 commands should give you an example of what you want as your outputs...
exec t_insert 'alwaysvalue'
select * from myTable
exec t_insert 'alwaysvalue', 'val1'
select * from myTable
exec t_insert 'alwaysvalue', 'val1', 'val2', 'val3'
select * from myTable
I know this is a very convoluted way of doing what you need to do.
You could probably equally select the default value from the InformationSchema for the relevant columns but to be honest, I might consider just adding the default value to param at the top of the procedure