Insert default value when parameter is null

后端 未结 16 2553
遥遥无期
遥遥无期 2020-12-24 05:27

I have a table that has a column with a default value:

create table t (
    value varchar(50) default (\'something\')
)

I\'m using a stored

16条回答
  •  清酒与你
    2020-12-24 05:49

    This is the best I can come up with. It prevents sql injection uses only one insert statement and can ge extended with more case statements.

    CREATE PROCEDURE t_insert (     @value varchar(50) = null )
    as
    DECLARE @sQuery NVARCHAR (MAX);
    SET @sQuery = N'
    insert into __t (value) values ( '+
    CASE WHEN @value IS NULL THEN ' default ' ELSE ' @value ' END +' );';
    
    EXEC sp_executesql 
    @stmt = @sQuery, 
    @params = N'@value varchar(50)',
    @value = @value;
    
    GO
    

提交回复
热议问题