如何删除检查约束?

How to remove check constraint?

我很难在 sql 中使用 Alter 删除 CHECK。谁能帮帮我?

CREATE TABLE MyProject_COST (
    ID int(4) NOT NULL UNIQUE,
    detail varchar2(25) NOT NULL,
    cost int(6) CONSTRAINT cost_project CHECK(cost>=500)
);

ALTER TABLE MyProject_COST ALTER COLUMN Cost int(6) 

Oracle 对此有 alter table ... drop constraint 语法。

但是由于您创建了一个匿名约束,所以这很棘手 - 因为您不知道约束的名称。

一个选项是使用动态 SQL 检索约束名称,并使用 execute immediate 命令删除它:

declare
    c_name varchar2(255 char);
begin

    select c.constraint_name into c_name
    from all_constraints c
    join all_cons_columns cc 
        on  cc.table_name = c.table_name 
        and cc.constraint_name = c.constraint_name
    where 
        cc.table_name = 'MYPROJECT_COST' 
        and cc.column_name ='COST'
        and c.constraint_type = 'C' ;

    if c_name is not null then
        execute immediate 
            'alter table myproject_cost drop constraint "' || c_name || '"';
    end if;
end;
/

Demo on DB Fiddle:

create table myproject_cost (
        id int not null unique,
        detail varchar2(25) not null,
        cost int check(cost >= 500)
    );

insert into MyProject_COST(id, detail, cost) values(1, 'foo', 0);
-- ORA-02290: check constraint (FIDDLE_XUVVCZVSYWWROHKPBFUF.SYS_C0030623) violated

declare
    c_name varchar2(255 char);
begin

    select c.constraint_name into c_name
    from all_constraints c
    join all_cons_columns cc 
        on  cc.table_name = c.table_name 
        and cc.constraint_name = c.constraint_name
    where 
        cc.table_name = 'MYPROJECT_COST' 
        and cc.column_name ='COST'
        and c.constraint_type = 'C' ;

    if c_name is not null then
        execute immediate 
            'alter table myproject_cost drop constraint "' || c_name || '"';
    end if;
end;
/
-- 1 rows affected

insert into MyProject_COST(id, detail, cost) values(1, 'foo', 0);
-- 1 rows affected