2013-05-19 23 views
3

我是新來的數據庫,我有一個關於觸發器或檢查約束表的問題。我正在使用SQL Server Mangagement工作室。硬觸發/制約

我有以下表:

create table item(
    startprice  char(5)   not null, 
    description  char(22)   not null, 
    start_date  char(10)   not null, 
    end_date   char(10)   not null, 
    indicator   char(3)   not null 

);

什麼,我想說明的是這種觸發/約束規則:indicator會得到「沒有」,如果系統日期是早於start_dateend_date,和「是」如果系統日期是start_date後。

+1

進行測試,我認爲你需要一個觸發,因爲'CHECK'僅用於確保字段的值滿足約束。你使用的是什麼RDBMS? –

+0

您正在使用哪個數據庫?甲骨文? Microsoft SQL Server? MySQL的? –

+0

我會建議觸發器,計算列或視圖,但是對於每個RDBMS,sql語法都不相同。 –

回答

1

這很簡單,你必須使用觸發器與before insert選項 -

以下觸發器是良好的Oracle數據庫中去 -

CREATE OR REPLACE TRIGGER item_insert_indicator 
BEFORE DELETE ON item 
For each row 
begin 
if :New.start_date > sysdate and :new.end_date > sysdate then 
    :New.indicator := 'no'; 
elsif :New.start_date < sysdate 
    :New.indicator := 'yes'; 
end if; 
end; 

這只是供大家參考。對於數據庫,您可以相應地更改關鍵字。

+0

如果我現在有sql服務器? – Allan

1

如果indicator只計算通過插入,然後我會建議去與新列created節省SYSDATE,並具有indicatorcomputed column

ALTER TABLE item ADD created datetime not null default getdate() 

ALTER TABLE item ADD indicator AS 
    case when created < start_date then 'no' else 'yes' end 
    PERSISTED 

Trigger也是一個不錯的選擇:

CREATE TRIGGER item_indicator 
ON item 
FOR INSERT, UPDATE 
AS 
    update inserted set indicator 
    = case when getdate() < start_date then 'no' else 'yes' end 
GO 

以及create new view(如果您在系統日期列中保留created列):

create view item2 as 
    select ... 
    , case when created < start_date then 'no' else 'yes' end as indicator 
    from item 

如果您需要做許多疑問indicator的話,我會去與持久化計算列或觸發+上indicator添加索引更好。

如果在每次更新時計算出值,那麼觸發器似乎是最合適的。

的這些例子沒有在現實情況下:)

+0

這是alter table,它可以用於現有的數據..但是新數據將被插入到表中呢? –

+0

正如我所知,在SQL Server中,如果未設置值(或空值?),並且在alter table alter table「add/change default」 - 對於所有空值,則在每個插入點上計算默認值。所以它應該工作,但我強烈建議嘗試所有情況;) –