本章介紹數(shù)據(jù)庫中的各種制約。
若要強(qiáng)制數(shù)據(jù)庫的完整性,一組規(guī)則的定義,也就是所謂約束。約束即允許或禁止在所述列中的值。
在實(shí)時(shí)數(shù)據(jù)庫活動(dòng),該數(shù)據(jù)應(yīng)該有一定的限制被添加。例如,在一個(gè)銷售數(shù)據(jù)庫,銷售-ID或事務(wù)id應(yīng)該是唯一的。約束類型是:
約束只能與表關(guān)聯(lián)。它們被施加到唯一特定的表。它們被定義和應(yīng)用于表在創(chuàng)建表時(shí)。
它是一個(gè)規(guī)則來從表內(nèi)的一個(gè)或多個(gè)列禁止空值。
語法:
db2 create table <table_name>(col_name col_type not null,..)
示例:[在此加入“not null”約束所有列,以避免形成表中的任何空單元格創(chuàng)建銷售表,四列(id, itemname, qty, price)]
db2 create table shopper.sales(id bigint not null, itemname varchar(40) not null, qty int not null,price double not null)
如下圖所示,可以插入表中的值:
例如:[錯(cuò)誤查詢]
db2 insert into shopper.sales(id,itemname,qty) values(1,'raagi',12)
輸出:[正確的查詢]
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
示例:[正確的查詢]
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)
輸出:
DB20000I The SQL command completed successfully.
使用這些限制,可以設(shè)置唯一的列值。對(duì)于這一點(diǎn),唯一約束使用“not null”約束在創(chuàng)建表時(shí)聲明。
語法:
db2 create table <tab_name>(<col> <col_type> not null unique, ...)
例如:
db2 create table shopper.sales1(id bigint not null unique, itemname varchar(40) not null, qty int not null,price double not null)
示例:要插入四個(gè)不同的行的唯一ID為1,2,3和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)
示例:[要插入新行“ID”值為3]
db2 insert into shopper.sales1(id, itemname, qty, price) values(3, 'cheese', 60,上一篇:DB2索引下一篇:DB2序列