DB2-제약

이 장에서는 데이터베이스의 다양한 제약에 대해 설명합니다.

소개

데이터베이스 무결성을 강화하기 위해 제약 조건이라고하는 일련의 규칙이 정의됩니다. 제약 조건은 열의 값을 허용하거나 금지합니다.

실시간 데이터베이스 활동에서 데이터는 특정 제한과 함께 추가되어야합니다. 예를 들어, 판매 데이터베이스에서 판매 ID 또는 거래 ID는 고유해야합니다. 제약 유형은 다음과 같습니다.

  • NULL 아님
  • Unique
  • 기본 키
  • 외래 키
  • Check
  • Informational

제약 조건은 테이블에만 연결됩니다. 특정 테이블에만 적용됩니다. 테이블 생성시 테이블에 정의되고 적용됩니다.

각 제약에 대한 설명 :

NULL 아님

테이블 내의 하나 이상의 열에서 null 값을 금지하는 것이 규칙입니다.

Syntax:

db2 create table <table_name>(col_name col_type not null,..)

Example: [판매 테이블을 만들려면 4 개의 열 (id, itemname, qty, price)을 사용하여 테이블에 null 셀이 형성되지 않도록 모든 열에 "not null"제약 조건을 추가합니다.]

db2 create table shopper.sales(id bigint not null, itemname 
varchar(40) not null, qty int not null,price double not null)

테이블에 NOT NULL 값 삽입

아래와 같이 테이블에 값을 삽입 할 수 있습니다.

Example: [ERROR 원 쿼리]

db2 insert into shopper.sales(id,itemname,qty) 
values(1,'raagi',12)

Output: [올바른 검색어]

DB21034E  The command was processed as an SQL statement because 
it was not a 

valid Command Line Processor command.  During SQL processing 
it returned: 

SQL0407N  Assignment of a NULL value to a NOT NULL column 
"TBSPACEID=5, 

TABLEID=4, COLNO=3" is not allowed.  SQLSTATE=23502

Example: [올바른 검색어]

db2 insert into shopper.sales(id,itemname,qty,price) 
values(1,'raagi',12, 120.00)  

db2 insert into shopper.sales(id,itemname,qty,price) 
values(1,'raagi',12, 120.00)

Output:

DB20000I The SQL command completed successfully.

고유 한 제약

이러한 제약 조건을 사용하여 열 값을 고유하게 설정할 수 있습니다. 이를 위해 고유 제약은 테이블 생성시“not null”제약으로 선언된다.

Syntax:

db2 create table <tab_name>(<col> <col_type> not null unique, ...)

Example:

db2 create table shopper.sales1(id bigint not null unique, 
itemname varchar(40) not null, qty int not null,price 
double not null)

테이블에 값 삽입

Example: 고유 ID가 1, 2, 3 및 4 인 4 개의 다른 행을 삽입하려면

db2 insert into shopper.sales1(id, itemname, qty, price) 
values(1, 'sweet', 100, 89)  

db2 insert into shopper.sales1(id, itemname, qty, price) 
values(2, 'choco', 50, 60)  

db2 insert into shopper.sales1(id, itemname, qty, price) 
values(3, 'butter', 30, 40)  

db2 insert into shopper.sales1(id, itemname, qty, price) 
values(4, 'milk', 1000, 12)

Example: "id"값이 3 인 새 행을 삽입하려면

db2 insert into shopper.sales1(id, itemname, qty, price) 
values(3, 'cheese', 60, 80)

Output: 기존 ID 값이있는 새 행을 삽입하려고하면 다음 결과가 표시됩니다.

DB21034E  The command was processed as an SQL statement 
because it was not a 

valid Command Line Processor command.  During 
SQL processing it returned: 

SQL0803N  One or more values in the INSERT statement, 
UPDATE statement, or foreign key update caused by a
DELETE statement are not valid because the primary key, 
unique constraint or unique index identified by "1" constrains 
table "SHOPPER.SALES1" from having duplicate values for the 
index key. SQLSTATE=23505

기본 키

고유 제약 조건과 유사하게 "기본 키"및 "외래 키"제약 조건을 사용하여 여러 테이블 간의 관계를 선언 할 수 있습니다.

Syntax:

db2 create table <tab_name>( 
      
       ,.., primary key ()) 
      

Example: "sid"를 기본 키로 사용하여 'salesboys'테이블 만들기

db2 create table shopper.salesboys(sid int not null, name 
varchar(40) not null, salary double not null, constraint 
pk_boy_id primary key (sid))

외래 키

외래 키는 다른 테이블에있는 행의 기본 키 하나 이상과 일치하는 데 필요한 테이블의 열 집합입니다. 참조 제한 또는 참조 무결성 제한입니다. 하나 이상의 테이블에있는 여러 열의 값에 대한 논리적 규칙입니다. 테이블 간의 필수 관계를 가능하게합니다.

이전에는 "shopper.salesboys"라는 이름의 테이블을 만들었습니다. 이 테이블에서 기본 키는 "sid"입니다. 이제 "employee"라는 다른 스키마와 "salesboys"라는 테이블을 사용하여 영업 소년의 개인 정보가 포함 된 새 테이블을 만듭니다. 이 경우 "sid"는 외래 키입니다.

Syntax:

db2 create table <tab_name>(<col> <col_type>,constraint 
<const_name> foreign key (<col_name>)  
                  reference <ref_table> (<ref_col>)

Example: [외래 키 열 'sid'가있는 'salesboys'라는 테이블을 만들려면]

db2 create table employee.salesboys( 
            sid int,  
            name varchar(30) not null,  
            phone int not null,  
            constraint fk_boy_id  
            foreign key (sid)  
            references shopper.salesboys (sid) 
			 on delete restrict 
                       )

Example: [기본 키 테이블“shopper.salesboys”에 값 삽입]

db2 insert into shopper.salesboys values(100,'raju',20000.00), 
(101,'kiran',15000.00), 
(102,'radha',10000.00), 
(103,'wali',20000.00), 
(104,'rayan',15000.00)

Example: [외래 키 테이블“employee.salesboys”에 값 삽입 [오류 없음]]

db2 insert into employee.salesboys values(100,'raju',98998976), 
(101,'kiran',98911176), 
(102,'radha',943245176), 
(103,'wali',89857330),  
(104,'rayan',89851130)

"shopper.salesboys"테이블에 저장되지 않은 알 수없는 번호를 입력하면 SQL 오류가 표시됩니다.

Example: [오류 실행]

db2 insert into employee.salesboys values(105,'rayan',89851130)

Output:

DB21034E  The command was processed as an SQL statement because it 
was not a valid Command Line Processor command.  During SQL 
processing it returned: SQL0530N  The insert or update value of 
the FOREIGN KEY "EMPLOYEE.SALESBOYS.FK_BOY_ID" is not equal to any 
value of the parent key of the parent table.  SQLSTATE=23503

제약 조건 확인

이 제약 조건을 사용하여 테이블의 특정 열에 대한 조건부 제한을 추가해야합니다.

Syntax:

db2 create table 
      
        (
        
        
          primary key (
         
          ), constraint 
          
            check (condition or condition) ) 
          
         
        
       
      

Example: [To create emp1 table with constraints values]

db2 create table empl                                                     
 (id           smallint not null,                                         
  name         varchar(9),                                                
  dept         smallint check (dept between 10 and 100), 
  job          char(5)  check (job in ('sales', 'mgr', 'clerk')), 
  hiredate     date,                                                      
  salary       decimal(7,2),                                              
  comm         decimal(7,2),                                              
  primary key (id),                                                       
  constraint yearsal check (year(hiredate) > 1986 or salary > 40500)  
 )
 

Inserting values

You can insert values into a table as shown below:

db2 insert into empl values (1,'lee', 15, 'mgr', '1985-01-01' , 
40000.00, 1000.00) 

Dropping the constraint

Let us see the syntaxes for dropping various constraints.

Dropping UNIQUE constraint

Syntax:

db2 alter table <tab_name> drop unique <const_name>

Dropping primary key

Syntax:

db2 alter table <tab_name> drop primary key 

Dropping check constraint

Syntax:

db2 alter table <tab_name> drop check <check_const_name>  

Dropping foreign key

Syntax:

db2 alter table <tab_name> drop foreigh key <foreign_key_name>