2009-04-25 3 views
1

ich eine SQL-Tabelle in MSSQL geschrieben haben:Ändern SQL CONSTRAINT auf der Basis anderer Felder

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')) 
) 

Ich möchte auf der action_size Spalte eine Einschränkung setzen, so dass:

1) Wenn action_action ist ‚F 'dann action_size muss 0,00 sein 2 (oder null, wenn das mehr machbar ist)) wenn action_action etwas anderes ist, als ‚F‘ dann action_size muss größer als Null (dh> = 0,01)

Wie drücke ich das aus? Ich habe versucht:

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

... vergebens.

Ich schreibe dies in MSSQL 2005, aber möchte eine Lösung, die auch mit MySQL 5.1.34 funktioniert.

BTW, wenn Sie möchten, Kommentar zu meiner action_action Spalte, fühlen Sie sich frei. Es wird nie andere gültige Werte für action_action geben oder, wenn es solche gibt, wird es äußerst selten sein und es wird nur ~ 1 anderer gültiger Wert sein.

Antwort

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) 
) 

Wenn Sie wurden Schwimmer anstelle von Dezimalstellen verwenden, schreiben die Nullprüfung als:

ABS(action_size) > 0.01 

Da schwimmt nicht genau Null sein kann, vor allem nach einigen Mathematik.

Verwandte Themen