2015-06-20 85 views
0

我試圖建立一個庫數據庫。我想確保一本書可以一次只借給一個人。我沒有觸發器的經驗,所以我想我可能會問你。SQL庫觸發器

 create table "book" (
     "book_id"   INTEGER       not null, 
     "condition"    VARCHAR2(50), 
     "isbn"    VARCHAR2(50)     not null, 
     constraint PK_BOOK primary key ("book_id") 
    ); 

    create table "borrowed" (
    "book_id"   INTEGER       not null, 
    "borrowed_id"  INTEGER       not null, 
    "user_id"   INTEGER       not null, 
    "date_borrowing"  DATE       not null, 
    "date_returning" DATE       not null, 
    "returned"   SMALLINT      not null, 
    constraint PK_BORROWED primary key ("book_id", "borrowed_id") 
); 

屬性附加傷害 「返回」 剛剛yes或no值(1或0)

回答

0

你並不需要爲這個觸發。你借來的桌子應該像這樣構成。注意,這裏使用一個虛擬列,這需要的Oracle 11g +的:

create table borrowed (
    borrowed_id INTEGER not null primary key, -- this should be set to a unique id for each row, using your preferred method 
    book_id INTEGER not null, 
    user_id INTEGER not null, 
    date_borrowing DATE not null, 
    date_returning DATE not null, 
    date_actualreturn DATE, 
    returned as (case date_actualreturn is null then 0 else 1 end) 
); 

然後,你要date_actualreturn有每本書最多一個NULL值。您可以使用唯一的索引或約束來執行此操作:

create table borrowed (
    borrowed_id INTEGER not null primary key, -- this should be set to a unique id for each row, using your preferred method 
    book_id INTEGER not null, 
    user_id INTEGER not null, 
    date_borrowing DATE not null, 
    date_returning DATE not null, 
    date_actualreturn DATE, 
    returned as (case date_actualreturn is null then 0 else 1 end), 
    constraint unq_only_one_book_borrowed unique 
     (coalesce(date_actualreturn, date '1900-01-01'), book_id) 
); 

這會在該列上創建一個唯一約束。如果一本書沒有被退回,日期總是看起來一樣 - 所以同一本書不能被借用兩次。而且,瞧!沒有觸發器。

+0

我們正在使用Oracle 10g –

+0

@klimatomas。 。 。您仍然可以使用基於函數的索引創建唯一索引。虛擬列便於定義'返回',但約束不需要。 –