且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当参数为NULL时将DEFAULT值插入到列中

更新时间:2023-11-30 22:16:22

由于param_2只能是nullnot null之一,因此只有一个select会返回要插入的行:

As param_2 can only be one of null or not null only one of the selects will return a row to be inserted:

with i as (
    insert into my_table (val_1)
    select param_1
    where param_2 is null
)
insert into my_table (val_1, val_2)
select param_1, param_2
where param_2 is not null

如果有必要返回插入的值:

If it is necessary to return the inserted values:

with i_null as (
    insert into my_table (val_1)
    select param_1
    where param_2 is null
    returning *
), i_notnull as (
    insert into my_table (val_1, val_2)
    select param_1, param_2
    where param_2 is not null
    returning *
)
select * from i_null
union all
select * from i_notnull