db2 create table org_temp (
deptnumb smallint not null,
deptname varchar(14),
manager smallint,
division varchar(10),
location varchar(13)
not null)
db2 alter table org_temp
add unique (location)
db2 insert into org_temp
values (10, 'Head Office', 160, 'Corporate', '
New York')
DB20000I The SQL command completed successfully.
db2 insert into org_temp
values (15, 'New England', 50, 'Eastern', '
New York')
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 "MELNYK.ORG_TEMP" from having duplicate rows for those columns.
SQLSTATE=23505
惟一约束通过防止无意的复制有助于确保数据的完整性。本例中,它防止插入第二条指定 New York 为该组织某部门位置的记录。惟一约束是通过惟一索引来实施的。 “头号人物!” - 主键约束 主键约束(primary key constraint)确保了表中构成主键的一列或一组列的所有值是惟一的。主键用于识别表中的特定行。每个表只能有一个主键,但可以有几个惟一键。主键约束是惟一约束的特例,它是通过主索引来实施的。
必须将主键约束中所引用的列定义为非空(NOT NULL)。可在 CREATE TABLE 语句中使用 PRIMARY KEY 子句(图1和图2)或者在如下的 altER TABLE 语句中定义主键约束。 清单 3. 创建主键约束。EMPLOYEE 表中的 EMPNO 列不能为空,并可在其上定义主键约束。
db2 update employee set empno = '350' where empno = '000190'
DB20000I The SQL command completed successfully.
db2 update employee set empno = '360' where empno = '000150'
SQL0531N The parent key in a parent row of relationship
"MELNYK.PROJECT.SQL040103212526610" cannot be updated. SQLSTATE=23504
db2 "select respemp from project where respemp < '000050' order by respemp"
RESPEMP
-------
000010
000010
000020
000030
000030
db2 delete from employee where empno = '000010'
DB20000I The SQL command completed successfully.
db2 "select respemp from project where respemp < '000050' order by respemp"
RESPEMP
-------
000020
000030
000030
您也可以使用 DB2 Control Center 来定义表检查约束(图 6)。 图 6. Alter Table 窗口提供了一个方便方式来定义一列上的表检查约束。
单击 Add 按钮以定义新约束(将打开 Add Check Constraint 窗口),或者单击 Change 按钮以修改在列表中选中的现有的约束(图7)。 图 7. Change Check Constraint 窗口让您修改现有的检查条件。
如果表中的现有行包含违反新约束的值,您就不能创建此表检查约束(图 8)。在适当更新了那些不兼容的值之后,您就可以成功添加或修改此约束了。 图 8. 如果新的表检查约束与表中现有的值不兼容,则会返回一条错误。
使用 SET INTEGRITY 语句可以打开或者关闭表检查约束。这将非常有用,例如,当在给表加载大型数据的期间优化性能时。清单 7 呈现了一个简单场景,展示了使用 SET INTEGRITY 语句的一种可能方式。本例中,将雇员“000100”的电话分机更新为 123,然后关闭 EMPLOYEE 表的完整性检查。在 EMPLOYEE 表上定义要求电话分机值为 4 位数字的检查约束。创建名为 EMPL_EXCEPT 的异常表;这个新表的定义是 EMPLOYEE 表的镜像。然后打开完整性检查,而违反检查约束的行将被写入异常表中。对这些表的查询将证实有问题的行现在仅存在于异常表中。 清单 7. 使用 SET INTEGRITY 语句来延迟约束的检查。
db2 update employee set phoneno = '123' where empno = '000100'
db2 set integrity for employee off
db2 alter table employee add constraint phoneno_length check (length(rtrim(phoneno)) = 4)
db2 create table empl_except like employee
db2 set integrity for employee immediate checked for exception in employee use empl_except
SQL3602W Check data processing found constraint violations and moved them to
exception tables. SQLSTATE=01603
db2 select empno, lastname, workdept, phoneno from empl_except
EMPNO LASTNAME WORKDEPT PHONENO
------ --------------- -------- -------
000100 SPENSER E21 123
1 record(s) selected.