【问题标题】:org.postgresql.util.PSQLException: ERROR: null value in column "order_id" violates not-null constraintorg.postgresql.util.PSQLException:错误:“order_id”列中的空值违反非空约束
【发布时间】:2016-01-14 11:25:57
【问题描述】:

我在postgresql中创建了一个存储过程,如下:

 INSERT INTO ABC

     (order_id,order_dt, customer_id, route_id, routenum, ordertype, create_station_id, create_stationtype, create_time,create_user_id,tran_time, tran_user_id,station_id)

   values 

     (1,$1, $2, $3, $4, $5, $6, $7, LOCALTIMESTAMP, $8, 

    default, default,$9) 

   returning  order_id;

order_idSERIAL 的类型 -> primary key

插入时出现如下错误:

PSQLException: ERROR: null value in column "order_id" violates not-null constraint Where: SQL function "insert_ABC" statement 1.

我正在使用PostgreSQL 8.2。它在我正在做的托管空间中。

我知道会发生错误,因为默认类型将 null 作为默认值。

SERIAL 类型的 default 的等价物是什么。

请指导我。

【问题讨论】:

    标签: sql postgresql stored-procedures


    【解决方案1】:

    您可以在INSERT INTO 中跳过order_id

    CREATE TABLE ABC(order_id SERIAL PRIMARY KEY, order_dt INT -- rest of cols
                    );
    
    INSERT INTO ABC(order_dt)  -- rest of cols
    VALUES (2)                 -- rest of values
    RETURNING order_id;
    

    或使用default:

    INSERT INTO ABC(order_id, order_dt)
    VALUES (default, 2)
    RETURNING order_id;
    

    编辑:

    你确定吗?查看演示:

    CREATE TABLE ABC(order_id SERIAL, order_dt INT);
    
    INSERT INTO ABC(order_dt)  -- rest of cols
    VALUES (2) ;  
    
    INSERT INTO ABC(order_id, order_dt)
    VALUES (default, 2) ; 
    

    SqlFiddleDemo

    输出:

    ╔═══════════╦══════════╗
    ║ order_id  ║ order_dt ║
    ╠═══════════╬══════════╣
    ║        1  ║        2 ║
    ║        2  ║        2 ║
    ╚═══════════╩══════════╝
    

    尝试使用 SQLFiddle 执行:

    CREATE TABLE ABC(order_id SERIAL NULL, order_dt INT);
    -- ERROR: conflicting NULL/NOT NULL declarations for 
    -- column "order_id" of table "abc"
    

    我没有使用PostgreSQL 8.2 对其进行测试的环境,但如果允许使用NULL 定义order_id,您应该将架构更改为NOT NULL

    【讨论】:

    • default 不会工作,因为它正在获取 NULL 值,而这里 order_id 是主键而不是 null。
    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2020-03-17
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多