Insert default value when parameter is null

后端 未结 16 2476
遥遥无期
遥遥无期 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:55

    Probably not the most performance friendly way, but you could create a scalar function that pulls from the information schema with the table and column name, and then call that using the isnull logic you tried earlier:

        CREATE FUNCTION GetDefaultValue
        (
            @TableName VARCHAR(200),
            @ColumnName VARCHAR(200)
        )
        RETURNS VARCHAR(200)
        AS
        BEGIN
            -- you'd probably want to have different functions for different data types if
            -- you go this route
        RETURN (SELECT TOP 1 REPLACE(REPLACE(REPLACE(COLUMN_DEFAULT, '(', ''), ')', ''), '''', '') 
                FROM information_schema.columns
                WHERE table_name = @TableName AND column_name = @ColumnName)
    
        END
        GO
    

    And then call it like this:

    INSERT INTO t (value) VALUES ( ISNULL(@value, SELECT dbo.GetDefaultValue('t', 'value') )
    

提交回复
热议问题