Как удалить constraint oracle
Устраните ограничение PRIMARY KEY на таблицу DEPT2 и удалите связанное ограничение FOREIGN KEY на столбец EMP2 . DEPARTMENT_ID :
Для удаления ограничения можно определить имя ограничения из представлений словаря данных USER_CONSTRAINTS и USER_CONS_COLUMNS . Затем используйте инструкцию ALTER TABLE с предложением DROP . Параметр CASCADE предложения DROP обеспечивает также удаление всех зависимых ограничений.
ALTER TABLE table DROP PRIMARY KEY | UNIQUE (column) | CONSTRAINT constraint [CASCADE]; |
table имя таблицы;
column имя столбца, на который действует ограничение;
constraint имя ограничения.
Когда удалено ограничение целостности, это ограничение больше не применяется принудительно сервером Oracle и больше не доступно в словаре данных.
SQL — Ограничения
От автора: ограничения SQL — это правила, применяемые к столбцам данных таблицы. Они используются, чтобы ограничить типы данных, которые могут храниться в таблице. Это обеспечивает точность и надежность данных в базе данных.
Ограничения могут применяться либо на уровне столбцов, либо на уровне таблицы. Ограничения на уровне столбца применяются только к одному столбцу, тогда как ограничения уровне таблицы применяются ко всей таблице.
Ниже приведены некоторые из наиболее часто используемых ограничений, доступных в SQL. Эти ограничения уже рассматривались в главе «Концепции SQL-RDBMS» , но сейчас мы вернемся к ним еще раз.
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC
В курсе 39 уроков | 15 часов видео | исходники для каждого урока
Ограничения могут указываться при создании таблицы с помощью оператора CREATE TABLE или вы можете использовать оператор ALTER TABLE для создания ограничений уже после создания таблицы.
Удаление ограничений
Любое ограничение, которое вы определили, можно удалить с помощью команды ALTER TABLE с параметром DROP CONSTRAINT.
Например, чтобы удалить ограничение первичного ключа в таблице EMPLOYEES, вы можете использовать следующую команду.
SQL Ключевое слово DROP CONSTRAINT
Команда DROP CONSTRAINT используется для удаления уникального, первичного ключа, внешнего ключа или ограничения проверки.
Отбросить уникальное ограничение
Чтобы удалить уникальное ограничение, используйте следующий SQL:
SQL Server / Oracle / MS Access:
Отбросить ограничение первичного ключа
Чтобы удалить ограничение первичного ключа, используйте следующий SQL:
SQL Server / Oracle / MS Access:
Отбросить ограничение внешнего ключа
Чтобы удалить ограничение внешнего ключа, используйте следующий SQL:
SQL Server / Oracle / MS Access:
Отбросить ограничение проверки
Чтобы удалить ограничение CHECK, используйте следующий SQL:
SQL Server / Oracle / MS Access:
Упражнения
Тесты
КАК СДЕЛАТЬ
ПОДЕЛИТЬСЯ
СЕРТИФИКАТЫ
Сообщить об ошибке
Если вы хотите сообщить об ошибке или сделать предложение, не стесняйтесь, присылайте нам электронное письмо:
Ваше предложение:
Спасибо, за вашу помощь!
Топ Учебники
Топ Справочники
Топ Примеры
Веб Сертификаты
SchoolsW3 оптимизирован для обучения, тестирования и тренировки. Примеры упрощают и улучшают чтение и базовое понимание. Учебники, справочники, примеры постоянно пересматриваются, для того, чтобы избежать ошибки, невозможно гарантировать правильность всего содержимого. Используя данный сайт, вы соглашаетесь прочитать и принять условия использования, cookie и Политика конфиденциальности. Авторское право 1999 — 2021 Все права защищены.
Работает на W3.CSS.
Помню несколько лет назад надо было почистить схему, удалив CONSTRAINTы из табличек.
При этом база вела себя как хотела: то сама удаляла индексы и ругалась при их повторном удалении, то оставляла их. Тогда дело решилось простой обработкой exception, сейчас пришла пора разобраться что тут к чему.
При удалении CONSTRAINT возможны следующие варианты:
Вариант 1: ALTER TABLE tbl DROP CONSTRAINT cons – базовый вариант, который все обычно и пишут
Вариант 2: ALTER TABLE tbl DROP CONSTRAINT cons CASCADE – расширеный вариант, который на самом деле удаляет связанные foreign key
Вариант 3: ALTER TABLE tbl DROP CONSTRAINT cons CASCADE DROP INDEX – машина для убийств
Опция cascade управляет только foreign key, которые ссылаются на таблицы
Далее мы не будет использовать опцию cascade, т.к. у нас будет одна таблица
Когда нужно добавлять DROP INDEX, а когда индекс удалится сам? Ответ простой: DROP INDEX лучше добавлять всегда, когда хочется гарантировано удалить индекс.
Для того, что бы ответить на вопрос, когда индекс удалится сам, проведем следующий набор тестов:
Тест 1: primary key + атоматически создаваемый (уникальный индекс)
Тест 2: primary key + вручную созданный уникальный индекс
Тест 3: primary key + вручную созданый неуникальный индекс
Для каждого из тестов попробуем удалить индекс без опции (вариант 1) и с опцией (вариант 3)
как видно, если индекс создается автоматически, то он удаляется в любом случае
Как видно, если индекс создавался вручную, то он не удаляется, если не указать DROP INDEX
Теперь сделаем constraint на обычном индексе. Этот вариант пробую из-за на достаточно подробном, но немного ошибочном посте Ричарда Фута
Как видно, если индекс создавался вручную, то он не удаляется, если не указать DROP INDEX
И последний вариант, который узнал из вышеуказанного поста Фута, основанный на DEFFERABLE CONSTRAINT. Для его поддержки Oracle автоматически создает неуникальный индекс
Вывод: без DROP INDEX удаление CONSTRAINT не удаляет даже автоматически создаваемые индексы
Итого
Для того, что бы гарантировано удалить индекс – добавляйте DROP INDEX к команде. В противном случае индекс удаляется только если он был автоматически создан и является уникальным (т.е. в одном случае из четырех)
How can I disable all table constrains in Oracle with a single command? This can be either for a single table, a list of tables, or for all tables.
11 Answers 11
It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.
It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.
Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.
@David I think I ran into this issue with the first segment. I solved it by adding 'DESC' between 'ORDER BY c.constraint_type' and the closing ')'
@WW My appreciation. This just saved me the trouble of writing a SQL statement to generate the Enable and Disable constraint statements.
Primary keys cannot be disabled on index-organized tables. You can handle these by adding AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P') to the first code segment.
Warning: if you have already DISABLED contraints, all constraints will be activated using that PL/SQL procedure. You have to filter those contraints on the where to ensure they keep disabled.
To take in count the dependencies between the constraints:
It's not a single command, but here's how I do it. The following script has been designed to run in SQL*Plus. Note, I've purposely written this to only work within the current schema.
To restrict what you drop, filter add a where clause to the select statement:-
- filter on constraint_type to drop only particular types of constraints
- filter on table_name to do it only for one or a few tables.
To run on more than the current schema, modify the select statement to select from all_constraints rather than user_constraints.
Note - for some reason I can't get the underscore to NOT act like an italicization in the previous paragraph. If someone knows how to fix it, please feel free to edit this answer.
If you want to DISABLE the constraints instead of DROPing them, simply edit the above SELECT statement: ' drop constraint ' to read ' disable constraint ' HTH :o)
Yes, that's a good suggestion - in the future, feel free to edit the post to add this information. That's why I have my posts as community wiki editable.
Use following cursor to disable all constraint.. And alter query for enable constraints.
This can be scripted in PL/SQL pretty simply based on the DBA/ALL/USER_CONSTRAINTS system view, but various details make not as trivial as it sounds. You have to be careful about the order in which it is done and you also have to take account of the presence of unique indexes.
The order is important because you cannot drop a unique or primary key that is referenced by a foreign key, and there could be foreign keys on tables in other schemas that reference primary keys in your own, so unless you have ALTER ANY TABLE privilege then you cannot drop those PKs and UKs. Also you cannot switch a unique index to being a non-unique index so you have to drop it in order to drop the constraint (for this reason it's almost always better to implement unique constraints as a "real" constraint that is supported by a non-unique index).
Modify physical characteristics (INITRANS or storage parameters)
We can modify the storage parameter of the table using Alter table statement. We can modify inittrans like this
Moving the table to new segments or tablespace
We can move the non-partition table or partition of the table to a new segment or new tablespace if required
We can even use the move command to change any storage parameter of the tables which are not modified using alter table command
Alter Table in oracle to Change Data Type
We can change the data type of any column using alter table modify command
Add a new column/Drop a column/rename a column
We can add a new column to the table definition
Using alter table add command
Oracle allows you to rename existing columns in a table. Use the RENAME COLUMN clause of the ALTER TABLE statement to rename a column
Oracle allows you to drop the column in the table using the command
Alter table drop column;
Please check the below article to learn about these in details
Set A Column Unused and Drop the unused column
if you are concerned about the resource consumed in dropping the column then you can use the ALTER TABLE…SET UNUSED statement.
- A column that is marked as unused is not displayed in queries or data dictionary views, and its name is removed so that a new column can reuse that name. All constraints, indexes, and statistics defined on the column are also removed.
We can drop the unused column later on when the resource is lower using the command
Add, modify or drop integrity constraints associated with the table or you can enable/disable the constraints also
Add constraints is done using alter table add constraints
Dropping Constraints – is done using the
Enabling/Disabling Constraints – Constraints can be created in DISABLE/ENABLE mode or can be disabled or enabled using the command
Rename table name
Oracle allows you to rename the table name also
Alteration of table cache/no-cache, Compression, parallelism
Oracle allows Alteration of table cache/no-cache, Compression, parallelism
Constraints are the ways to enforce data integrity rules in the Oracle database. If we dont require constraint at any point of time, we can drop constraint in Oracle using the alter table command. Lets check with the addition of constraint and then dropping them
Oracle Table creation and Constraint creation
Here we have created two tables and created constraints for primary key, foreign key ,check constraint.Now that we have created the constraints,lets see how we can drop the constraint in oracle
Drop the constraint can be simply done by
We can drop primary key constraint, unique key constraint, foreign key constraint , check constraint and non null constraint using the same command given above. We just need to first find all the constraints on the table and then drop them according to the need.
Table of Contents
drop foreign key constraint oracle
drop primary key constraint in oracle
We can also drop the Primary key constraint by specifying the column name
Important Note
You cannot drop a primary key or unique key constraint that is part of a referential integrity constraint without also dropping the foreign key. To drop the referenced key and the foreign key together, use the CASCADE clause. If you omit CASCADE, then Oracle Database does not drop the primary key or unique constraint if any foreign key references it.
Drop Not null or check constraints
Now Dropping the Not Null constraints
drop unique constraint oracle
Now the table is created, we can drop the constraint using the below statement
We can drop the unique constraint by specifying the column name also
Drop all the constraint in Oracle
You can drop all the constraints in the table using the below procedure also
We learn how to drop constraint in oracle. The constraint could be primary key, Unique key, foreign key and check constraint.
I hope you like this article and it helps in your day to day working. Please let me know the feedback on this.
Читайте также: