2013-10-22 198 views
2

我有以下表格:SQL ALTER TABLE ON DELETE CASCADE

CREATE TABLE BOOK_AUTHORS 
(Book_id CHAR(20) NOT NULL, 
AuthorName VARCHAR(30) NOT NULL, 
PRIMARY KEY (Book_id, AuthorName), 
FOREIGN KEY (Book_id) REFERENCES BOOK (Book_id)); 

CREATE TABLE BOOK_COPIES 
(Book_id CHAR(20) NOT NULL, 
Branch_id CHAR(20) NOT NULL, 
No_of_copies NUMBER, 
PRIMARY KEY (Book_id, Branch_id), 
FOREIGN KEY (Book_id) REFERENCES BOOK (Book_id), 
FOREIGN KEY (Branch_id) REFERENCES LIBRARY_BRANCH (Branch_id)); 

我想ON DELETE CASCADE約束添加到他們兩個:

我第一次嘗試它說,它的工作。這個文件看起來像:

ALTER TABLE "BOOK_AUTHORS" 
ADD CONSTRAINT "fk_test" 
FOREIGN KEY ("Book_id") 
REFERENCES "BOOK" ("Book_id") 
ON DELETE CASCADE; 

然後我去通過,並在第二個表由兩個獨立的表的兩個外鍵:

ALTER TABLE "BOOK_COPIES" 
ADD CONSTRAINT "fk_test1" 
FOREIGN KEY ("Book_id") 
REFERENCES "BOOK" ("Book_id") 
ON DELETE CASCADE; 

ALTER TABLE "BOOK_COPIES" 
ADD CONSTRAINT "fk_test2" 
FOREIGN KEY ("Branch_id") 
REFERENCES "LIBRARY_BRANCH" ("Branch_id") 
ON DELETE CASCADE; 

然而,在這樣做,我得到了錯誤

「Book_id」 無效的標識符

然後

「Branch_id」 無效的標識符

我不知道我做錯了什麼。然後,我又回去做了第一個更改表(我原本以爲工作的那個),它給了我同樣的錯誤信息("Book_id" invalid identifier)。有人可以幫我添加這些限制嗎?我還有其他五個表來添加這些約束。

+0

確表'LIBRARY_BRANCH'有字段'Branch_id'? –

+0

是的,這是我的LIBRARY_BRANCH表 CREATE TABLE LIBRARY_BRANCH (Branch_id CHAR(20)NOT NULL, Branch_name VARCHAR(50), 地址VARCHAR(100), PRIMARY KEY(Branch_id)); – Anon1234567890

+0

你是如何製作副本的?也許副本已經設置了外鍵? –

回答

0

認沽雙引號(「)。在你的表和列名

我添加表 」書「 和表 」LIBRARY_BRANCH「:

CREATE TABLE "BOOK" 
("Book_id" CHAR(20) NOT NULL, 
"BookName" VARCHAR(30) NOT NULL, 
PRIMARY KEY ("Book_id")); 

CREATE TABLE "BOOK_AUTHORS" 
("Book_id" CHAR(20) NOT NULL, 
"AuthorName" VARCHAR(30) NOT NULL, 
PRIMARY KEY ("Book_id", "AuthorName")); 

CREATE TABLE "LIBRARY_BRANCH" 
("Branch_id" CHAR(20) NOT NULL, 
"Branch_name" VARCHAR(50), 
"Address" VARCHAR(100), 
PRIMARY KEY ("Branch_id")); 

CREATE TABLE "BOOK_COPIES" 
("Book_id" CHAR(20) NOT NULL, 
"Branch_id" CHAR(20) NOT NULL, 
"No_of_copies" NUMBER, 
PRIMARY KEY ("Book_id", "Branch_id")); 


ALTER TABLE "BOOK_AUTHORS" 
ADD CONSTRAINT "fk_test" 
FOREIGN KEY ("Book_id") 
REFERENCES "BOOK" ("Book_id") 
ON DELETE CASCADE; 

ALTER TABLE "BOOK_COPIES" 
ADD CONSTRAINT "fk_test1" 
FOREIGN KEY ("Book_id") 
REFERENCES "BOOK" ("Book_id") 
ON DELETE CASCADE; 

ALTER TABLE "BOOK_COPIES" 
ADD CONSTRAINT "fk_test2" 
FOREIGN KEY ("Branch_id") 
REFERENCES "LIBRARY_BRANCH" ("Branch_id") 
ON DELETE CASCADE; 

sqlfiddle demo

3

如果你把雙引用圍繞你的標識符(就像你在

ALTER TABLE "BOOK_COPIES" 
ADD CONSTRAINT "fk_test1" 
FOREIGN KEY ("Book_id") 
REFERENCES "BOOK" ("Book_id") 
ON DELETE CASCADE; 

)您的標識符(例如本例中的「Book_id」)區分大小寫。

因此,無論你必須改變你的表定義,並重新命名列「Book_id」或(更優選恕我直言)剛剛獲得在你的約束定義去掉雙引號:

ALTER TABLE BOOK_COPIES 
ADD CONSTRAINT fk_test1 
FOREIGN KEY (Book_id) 
REFERENCES BOOK (Book_id) 
ON DELETE CASCADE; 
1

第一所有讓我明白一件事情,你不能添加刪除層疊到一個已經存在的外鍵約束,如docs所示,你只能改變它的狀態,這意味着啓用或禁用,如果你需要添加然後先刪除約束。這個問題被問及兩次,仍然重複,請管理員有一個這樣的一瞥。這裏是已經解決了你的問題的鏈接。 first,secondthird,誰知道在刪除級聯時詢問了多少個問題。