【问题标题】:Insert only non null values into SQL table仅将非空值插入 SQL 表
【发布时间】:2021-04-23 18:12:17
【问题描述】:

我尝试将值插入到我的表中,但我只想插入非空值,我需要忽略的空值不需要处理。我要插入的变量是 SQL 选择的结果,我试过了,但没有用:

insert into mytable(id)
values (case when (select id from tab2 where login=?) is not null then (select id from tab2 where login=?)) 

换句话说,我想插入与此条件相对应且不为空的 id。

【问题讨论】:

    标签: sql postgresql talend


    【解决方案1】:

    你可以这样做:

    insert into mytable(id)
    select id from tab2 
    where login=? and id is not null
    

    【讨论】:

    • 很遗憾不起作用,得到相同的消息:错误:“id”列中的空值违反非空约束
    • 如果只运行 select 语句,它会返回什么?
    • itgives just empty column with name id the problem in the insert it still give ERROR: null value in column "id"违反了非空约束,即使条件不为空
    • @Rana - 看看这个小提琴,它有效,你的问题是别的dbfiddle here
    • 实际上当您插入时应该添加值()?相反,您只需添加一个选择
    【解决方案2】:

    你可以试试这个,看看是否适合你:

    insert into mytable(id)
    select ID
    from tab2
    where id IS NOT NULL
      and login = ?
    

    【讨论】:

    • 没有工作错误:“id_compte”列中的空值违反非空约束
    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多