小编Rud*_*lan的帖子

基于另一列中的值的列约束

我有一个 PostgreSQL 表phase_steps,包含以下示例行:

phase_step_id|step_type|step_status|
-------------+---------+-----------+
            1| RESEARCH|           |
            2|   SURVEY|           |
        
Run Code Online (Sandbox Code Playgroud)

更新step_status列的值取决于该值 step_type是什么。
step_type为“RESEARCH”时,只能输入“COMPLETE”或“INCOMPLETE”值step_status
step_type为“SURVEY”时,只能输入“ASSIGNED”或“NOT ASSIGNED”值step_status

step_status我尝试通过以下过程管理“研究”约束:

create or replace function insert_step_status_value() returns trigger as $$
    begin
        if (new.step_status != 'COMPLETE') or (new.step_status != 'INCOMPLETE')
        from phase_steps where step_type = 'RESEARCH'
        then
            raise exception 'Status value not in range for this phase step';
        end if;
        return new;
    end;
$$ language plpgsql;

create trigger check_step_status_value before update …
Run Code Online (Sandbox Code Playgroud)

postgresql trigger database-design constraint check-constraints

6
推荐指数
1
解决办法
7905
查看次数