Insert default value when parameter is null

后端 未结 16 1974
遥遥无期
遥遥无期 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 06:02

    Try an if statement ...

    if @value is null 
        insert into t (value) values (default)
    else
        insert into t (value) values (@value)
    
    0 讨论(0)
  • 2020-12-24 06:06

    Don't specify the column or value when inserting and the DEFAULT constaint's value will be substituted for the missing value.

    I don't know how this would work in a single column table. I mean: it would, but it wouldn't be very useful.

    0 讨论(0)
  • 2020-12-24 06:07

    The easiest way to do this is to modify the table declaration to be

    CREATE TABLE Demo
    (
        MyColumn VARCHAR(10) NOT NULL DEFAULT 'Me'
    )
    

    Now, in your stored procedure you can do something like.

    CREATE PROCEDURE InsertDemo
        @MyColumn VARCHAR(10) = null
    AS
    INSERT INTO Demo (MyColumn) VALUES(@MyColumn)
    

    However, this method ONLY works if you can't have a null, otherwise, your stored procedure would have to use a different form of insert to trigger a default.

    0 讨论(0)
  • 2020-12-24 06:09

    The best option by far is to create an INSTEAD OF INSERT trigger for your table, removing the default values from your table, and moving them into the trigger.

    This will look like the following:

    create trigger dbo.OnInsertIntoT
    ON TablenameT
    INSTEAD OF INSERT
    AS
    insert into TablenameT
    select
       IsNull(column1 ,<default_value>)
      ,IsNull(column2 ,<default_value>)
      ...
    from inserted
    

    This makes it work NO MATTER what code tries to insert NULLs into your table, avoids stored procedures, is completely transparent, and you only need to maintain your default values in one place, namely this trigger.

    0 讨论(0)
提交回复
热议问题