我有一个用MSSQL编写的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(如果更可行,则为null)
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
的其他有效值,或者,如果有,它将非常罕见,并且只有〜1个其他有效值。
答案 0 :(得分: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 :(得分: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
因为浮点数可能不完全为零,特别是在数学之后。
答案 2 :(得分:0)