文档首页> 数据仓库服务 GaussDB(DWS)> 故障排除> 数据库使用> 插入数据报错:null value in column '%s' violates not-null constraint
更新时间:2024-02-27 GMT+08:00
分享

插入数据报错:null value in column '%s' violates not-null constraint

问题现象

向表中插入数据报错:null value in column '%s' violates not-null constraint,此处s%指报错的列(字段)名。

1
2
3
4
CREATE TABLE t1(a int, b int not null);

INSERT INTO t1 VALUES (1);
ERROR:  dn_6001_6002: null value in column "b" violates not-null constraint

原因分析

针对上述案例,表t1中的字段b在建表时,设置了非空(not null)约束,那么字段b中不能有空值。而插入数据时b列为空,则执行报错。

解决方案

针对上述案例,有两种解决方案:

  • 方案一:使用ALTER TABLE删除字段b的非空(not null)约束
    1
    2
    3
    4
    5
    ALTER TABLE t1 ALTER COLUMN b DROP NOT NULL;
    ALTER TABLE
    
    INSERT INTO t1 VALUES (1);
    INSERT 0 1
    
  • 方案二:保持字段b的非空(not null)约束,字段b不再插入空值

在实际业务中,可根据实际情况选择解决方案。

分享:

    相关文档

    相关产品