How to remove constraint based on columns from oracle database?

六眼飞鱼酱① 提交于 2019-12-10 20:39:51

问题


Is there is a way to remove a constraint (unique index) based on columns name?

What I would like to do is to remove a constraint where columna name is name, and name_type.

ALTER TABLE MY_TABLE DROP CONSTRAINT NAME_OF_CONSTRAINT;

I don't have a name so I would like to do it this way...

ALTER TABLE MY_TABLE DROP CONSTRAINT **WHERE COLUMN = col1 AND column = col2**

Any syntax to do something like this on a constraint.


回答1:


I didn't think this was possible with a single statement, but it turns out it is, as shown in the examples in the documentation:

ALTER TABLE MY_TABLE DROP UNIQUE(col1, col2);

A complete example: ALTER TABLE MY_TABLE ADD UNIQUE (col1, col2);

Table my_table altered.

SELECT CONSTRAINT_NAME, INDEX_NAME
FROM USER_CONSTRAINTS
WHERE TABLE_NAME = 'MY_TABLE';

CONSTRAINT_NAME                INDEX_NAME                    
------------------------------ ------------------------------
SYS_C0092455                   SYS_C0092455                   

ALTER TABLE MY_TABLE DROP UNIQUE(col1, col2);

Table my_table altered.

SELECT CONSTRAINT_NAME, INDEX_NAME
FROM USER_CONSTRAINTS
WHERE TABLE_NAME = 'MY_TABLE';

no rows selected

An alternative approach is to query the USER_CONSTRAINTS and USER_CONS_COLUMNS views to find the matching constraint name - presumably system-generated or you would already know it - and then use that name. If you need to do this as a script then you could query in a PL/SQL block, and plug the found constraint name into a dynamic ALTER TABLE statement.




回答2:


  1. Do a SELECT * FROM USER_CONS_COLUMNS or ALL_CONS_COLUMNS. This will give you the constraint name for the owner, table and column combination.
  2. Out of the multiple rows returned for a column name, use the constraint names as necessary in the ALTER TABLE ... DROP CONSTRAINT... syntax.
  3. Use dynamic sql to do it for all rows in a loop if you are absolutely sure that you can drop all of them.

This will give you an extra layer of protection so that you don't accidentally drop a constraint that was needed.



来源:https://stackoverflow.com/questions/28544816/how-to-remove-constraint-based-on-columns-from-oracle-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!