2009-04-25 49 views
1

我已經寫在MSSQL SQL表:更改SQL約束基於其他字段

create table [action] 
(
    action_id  bigint identity not null, -- PK 
    action_action char(1) not null,  -- 'C' Call, 'R' Raise, 'F' Fold, 'P' Post 
    action_size  decimal(9,2) not null, -- zero if fold, > zero otherwise 

    constraint pk_action primary key clustered (action_id), 
    constraint chk_action_action check (action_action in('C','R','F','P')) 
) 

我想提出一個約束的action_size列這樣的:

1)如果action_action是「F '然後action_size必須是0.00(或空,如果這是更可行的) 2)如果action_action比其他任何‘F’然後action_size必須大於零(即,> = 0.01)

如何我要表達這一點嗎?我試過:

constraint chk_action_size check (
    select action_action 
     case 'F' action_size = 0.00 
     else  action_size > 0.00 
) 

...無濟於事。

我在MSSQL 2005中寫這個,但想要一個與MySQL 5.1.34一起工作的解決方案。

順便說一句,如果你願意評論我的action_action專欄,請隨意。對於action_action,將不會有其他有效值,或者如果有的話,它將非常罕見,並且只會有其他有效值。

回答

2
create table [action] 
(
    action_id   bigint identity not null, 
    action_action  char(1) not null, 
    action_size   decimal(9,2) not null, 

    constraint pk_action primary key clustered (action_id), 
    constraint chk_action_action check (action_action in('C','R','F','P')), 
    constraint chk_action_size check 
    (
     (action_action = 'F' AND action_size = 0.00) OR 
     (action_action <> 'F' AND action_size > 0.00) 
    ) 
) 
1
ALTER TABLE action ADD CONSTRAINT chk_action_size CHECK (
    (action_action = 'F' AND action_size = 0.00) 
    OR (action_action <> 'F' AND action_size > 0.00) 
) 

如果您正在使用花車,而不是小數,寫零檢查爲:

ABS(action_size) > 0.01 

由於浮動可能不完全爲零,尤其是在一些數學。

相關問題