search
HomeDatabaseMysql TutorialOracle数据完整性约束:主键、外键、各种约束的创建删除语句

ORACLE对数据库完整性的约束: 三种方法维护数据完整性:ORACLE完整性约束,数据库触发器,应用程序代码。应尽量使用ORACLE完整性

Oracle对数据库完整性的约束: 

三种方法维护数据完整性:ORACLE完整性约束,数据库触发器,应用程序代码。

应尽量使用ORACLE完整性约束,可靠性和效率高,容易修改,使用灵活,记录在数据字典。

ORACLE五种约束:

非空 not null,定义 的列不能为空。只能在列级定义

唯一,unique,表中每一行所定义 的列或列值不能相同

主键primary key 不能包括空值,主键唯一标识表中每一行,一列或几列组合为主键

外键foreign key 指明一列或几列的组合为外键以维护从表chilD table和主表 parent table 之间的引用完整性referential integrity

条件约束check,表中每一行要满足约束条件。约束加上表上,创建表时可以定义

1.查询约束

查询表中是否有约束并显示约束名:显示表列所对应的约束的信息

BYS@bys1>select a.constraint_name, a.column_name from user_cons_columns a, user_constraints b where a.table_name = upper('&AA');
Enter value for aa: emp
old 1: select a.constraint_name, a.column_name from user_cons_columns a, user_constraints b where a.table_name = upper('&AA')
new 1: select a.constraint_name, a.column_name from user_cons_columns a, user_constraints b where a.table_name = upper('emp')

CONSTRAINT_NAME COLUMN_NAME
------------------------------ ---------------
PK_EMPNO EMPNO
查表中是否有主键约束

BYS@bys1>select a.constraint_name, a.column_name from user_cons_columns a, user_constraints b where a.constraint_name = b.constraint_name and b.constraint_type = 'P' and a.table_name =upper('&table_name');
Enter value for table_name: emp
old 1: select a.constraint_name, a.column_name from user_cons_columns a, user_constraints b where a.constraint_name = b.constraint_name and b.constraint_type = 'P' and a.table_name =upper('&table_name')
new 1: select a.constraint_name, a.column_name from user_cons_columns a, user_constraints b where a.constraint_name = b.constraint_name and b.constraint_type = 'P' and a.table_name =upper('emp')

CONSTRAINT_NAME COLUMN_NAME
------------------------------ ---------------
PK_EMPNO EMPNO

查当前用户下的所有约束的信息

BYS@bys1>col owner for a10
BYS@bys1>col table_name for a10
BYS@bys1>select * from user_cons_columns;
OWNER CONSTRAINT_NAME TABLE_NAME COLUMN_NAME POSITION
---------- ------------------------------ ---------- --------------- ----------
BYS PK_OBJ_ID TEST2 OBJECT_ID 1
BYS SYS_C0011203 TEST1 OBJECT_ID 1
BYS PK_EMPNO EMP EMPNO 1

 

查询当前用户的相关约束的状态信息,,可以查dba_constraints或USER_constraints

BYS@bys1>select constraint_name,table_name,constraint_type,status,deferrable,deferred,validated from dba_constraints where owner='BYS';
CONSTRAINT_NAME TABLE_NAME C STATUS DEFERRABLE DEFERRED VALIDATED
------------------------------ ---------- - -------- -------------- --------- -------------
SYS_C0011203 TEST1 P ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED
PK_EMPNO EMP P ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED
PK_OBJ_ID TEST2 P ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED

SCOTT@bys1>select constraint_name,table_name,constraint_type,status,deferrable,deferred,validated from user_constraints;
CONSTRAINT_NAME TABLE_NAME C STATUS DEFERRABLE DEFERRED VALIDATED
------------------------------ ---------- - -------- -------------- --------- -------------
FK_DEPTNO EMP R ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED
PK_DEPT DEPT P ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED
PK_EMP EMP P ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED
SYS_C0011265 TEST P ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED
PK_A TEST1 P ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED

2.增加、删除、修改约束 增加与修改:

增删主键及外键

alter table dept add constraint pk_dept primary key(deptno);

alter table dept2 add primary key(dname); 不指定约束名,则由系统自动命令约束名。
alter table emp add constraint fk_deptno foreign key(deptno) references dept(deptno) on delete cascade;
alter table emp add constraint fk_deptno foreign key(deptno) references dept(deptno);

注:on delete cascade和on delete set null的作用是用来处理级联删除问题的,

如果你需要删除的数据被其他数据所参照(主、外键),那么你应该决定到底希望oracle怎么处理那些参照这些即将要删除数据的数据的.

你可以有三种方式:
禁止删除,这也是oracle默认的。
将那些参照本值的数据的对应列赋空,使用on delete set null关键字。即删除本表的列中的值,对本列有外键引用的表的相应的列有相应值行会被修改为NULL。
将那些参照本值的数据一并删除,使用on delete cascade关键字,即删除本表的列中的值,对本列有外键引用的表的相应的列有相应值行会被删除

增加CHECK 约束:

alter table dept add constraint valid_deptno check (deptno); DEPTNO列的值需要少于5000

SQL>alter table customer add constraint abc check (address in (’海淀’,’朝阳’,’东城’,’西城’,’通州’,’崇文’,’昌平’)); 增加客户的住址只能是’海淀’,’朝阳’,’东城’,’西城’,’通州’,’崇文’,’昌平’;

增加惟一约束

alter table customer add constraint aaa unique(cardId);

增加非空约束--注意增加非空约束时用的是关键字modify,其它四种约束都是ADD

SQL>alter table dept modify dname not null;

删除

对非空约束的删除:因为非空约束不能指定约束名,应该先通过查询表和列所对应的的约束信息,找出约束名,再删除。如下:

BYS@bys1>alter table dept drop constraint SYS_C0011725;

修改约束--大可以删除了重建

alter table dept2 modify constraint pk_d2 initially immediate;

删除指定名字的约束---可以是主键、外建或其它约束的名字

alter table emp drop constraint PK_EMPNO;

alter table scott.event drop constraint evtid_pk; 删除其它用户的约束--需要DBA权限

不用指定约束名,直接删除表中主键

altertable emp drop primary key cascade; 删除主键约束的时候,如果在些主键上的外键创建时未指定on delete cascade参数,直接删除主键报错,要加上cascade参数。

重命令约束

alter table scott.emp rename constraint pk_emp to emp_empno_pk;

更多详情见请继续阅读下一页的精彩内容

相关阅读:

Oracle完整性约束

Oracle的约束和索引

从Oracle的约束到索引

Oracle常用数据类型和完整性约束

ORA-02291: 违反完整约束条件 …… - 未找到父项关键字

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

MySQL's Purpose: Storing and Managing Data EffectivelyMySQL's Purpose: Storing and Managing Data EffectivelyApr 16, 2025 am 12:16 AM

MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

SQL and MySQL: Understanding the RelationshipSQL and MySQL: Understanding the RelationshipApr 16, 2025 am 12:14 AM

The relationship between SQL and MySQL is the relationship between standard languages ​​and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor