如何删除check约束?

t3irkdon  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(518)

在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)
r6l8ljro

r6l8ljro1#

甲骨文确实有一个 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;
/

db小提琴演示:

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

相关问题