2013-10-16 56 views
0

我的教授希望我們在我們的數據庫類的代碼中填入一些空白。 我認爲我做得對,但我不確定自己是否正如我們剛剛開始討論的主題。 我不知道從哪裏開始第五個約束(IC5)如果有人可以給我一些方向或有用的來源。(Oracle)SQL DDL - 完整性約束

SPOOL ddl.out 
SET ECHO ON 
-- 
-- Author: 
-- 
-- IMPORTANT: use the names IC-1, IC-2, etc. as given below. 
-- -------------------------------------------------------------------- 
DROP TABLE Orders CASCADE CONSTRAINTS; 
DROP TABLE OrderLine CASCADE CONSTRAINTS; 
-- 
CREATE TABLE Orders 
( 
orderNum INTEGER PRIMARY KEY, 
priority CHAR(10) NOT NULL, 
cost INTEGER NOT NULL, 
/* 
IC1: The priority is one of: high, medium, or low 
*/ 
CHECK priority=('high' OR 'medium' OR 'low'), 
/* 
IC2: The cost of a high priority order is above 2000. 
*/ 
CHECK priority='high' AND cost>2000, 
/* 
IC3: The cost of a medium priority order is between 800 and 2200 (inclusive). 
*/ 
CHECK priority='medium' AND cost BETWEEN 800 AND 2200, 
/* 
IC4: The cost of a low priority order is less than 1000. 
*/ 
CHECK priority='low' AND cost<1000, 
); 
-- 
-- 
CREATE TABLE OrderLine 
( 
orderNum INTEGER, 
lineNum INTEGER, 
item CHAR (10) NOT NULL, 
quantity INTEGER, 
PRIMARY KEY (orderNum, lineNum), 
/* 
IC5: Every order line must belong to an order in the Order table. 
Also: if an order is deleted then all its order lines must be deleted. 
IMPORTANT: DO NOT declare this IC as DEFERRABLE. 
*/ 
<<< YOUR SQL CODE GOES HERE >>> 
); 
-- 
-- ---------------------------------------------------------------- 
-- TESTING THE SCHEMA 
-- ---------------------------------------------------------------- 
INSERT INTO Orders VALUES (10, 'high', 2400); 
INSERT INTO Orders VALUES (20, 'high', 1900); 
INSERT INTO Orders VALUES (30, 'high', 2100); 
INSERT INTO Orders VALUES (40, 'medium', 700); 
INSERT INTO Orders VALUES (50, 'low', 1100); 
INSERT INTO Orders VALUES (60, 'low', 900); 
SELECT * from Orders; 
+0

IC1可以更短; IC2,IC3,IC4都是錯誤的 - 它們不允許任何其他值超出您所指定的值。 –

回答

1

你需要的是一個外鍵約束。

1

IC5:

FOREIGN KEY (orderNum) REFERENCES Orders (orderNum) ON DELETE CASCADE 
+0

您的語法無效;反引號在這裏是不允許的(至少對於Oracle來說)。 –

+0

對不起,你是對的。編輯我的答案。 – 2013-10-16 11:28:10