由于表结构的变动需要删除,现有的主键约束,增加新的主键约束.但主键约束没有指定约束名生成,无法直接删除该主键约束.
需要先查询出主键约束名,然后才能够进行删除
原本是想通过该sql 语句在查询的时候直接进行删除,但是sql一直提示报错,原因不明白.
alter table 表名 drop constraint (select a.constraint_name from user_cons_columns A,user_constraints B
where A.constraint_name=B.constraint_name and A.table_name='表名' and B.constraint_type='P')
后来想通过块的方式,将变量对应的值给相应的sql,但是也失败了,可能结果与上述的sql写法内核是一致的,最终通过拼接sql语句的办法总算是解决了
以下是成功代码
--删除原有的主键约束
--添加id字段
--更新主键约束为ID
DECLARE sql_drop_pri VARCHAR2(64);
constraintName VARCHAR2(64) DEFAULT '0';
BEGIN
select 'alter table 表名 drop constraint ' || (select a.constraint_name from user_cons_columns A,user_constraints B
where A.constraint_name=B.constraint_name and A.table_name='表名' and B.constraint_type='P') into sql_drop_pri from dual;
select a.constraint_name INTO constraintName from user_cons_columns A,user_constraints B
where A.constraint_name=B.constraint_name and A.table_name='表名' and B.constraint_type='P';
if constraintName !='0' then
execute immediate sql_drop_pri;
end if;
--不抛出异常的话就会报no_data_found即使对相应的变量进行nvl()函数处理也没用
exception when no_data_found then
constraintName :='0';
END;