[英]check constraint with if logic oracle sql
Is there a way to use if logic in an oracle sql check constraints?有没有办法在oracle sql检查约束中使用if逻辑?
This is my pseudo table:这是我的伪表:
create table child
(
name,
behaviour,
treat,
);
Now what i want is that if the behaviour
of child = 'bad'
then treat != 'lollies'
.现在我想的是,如果behaviour
的孩子= 'bad'
再treat != 'lollies'
。
Sometimes it is easier to express using NOT to define what is not allowed:有时使用 NOT 来定义不允许的内容更容易表达:
CHECK (NOT (behaviour = 'bad' AND treat = 'lollies'))
... which means same as: ...这意味着相同:
CHECK (behaviour != 'bad' OR treat != 'lollies')
It is easy to get this wrong, as other answers have shown!正如其他答案所示,这很容易出错!
ALTER TABLE child
ADD CONSTRAINT bad_behaviour_CK
CHECK (NOT (behaviour = 'bad' AND treat = 'lollies')) ;
Tesed in SQL-Fiddle在SQL-Fiddle 中测试
If you have learned propositional logic before, we can apply it in this situation and explain how the top voted answer is derived.如果你之前学过命题逻辑,我们可以在这种情况下应用它,并解释如何推导出最高投票的答案。
We let A be the proposition of behavior = 'bad'
and B be the proposition of treat != 'lollies'
.我们让A是behavior = 'bad'
的命题, B是treat != 'lollies'
的命题。 The statement of "If behavior = 'bad'
, then treat != 'lollies'
" can be written as " A → B ". “If behavior = 'bad'
, treat != 'lollies'
”的语句可以写成“ A → B ”。
Note that " A → B " is logically equivalent to "¬ A ∨ B " (¬ means NOT and ∨ means OR).请注意,“ A → B ”在逻辑上等同于“¬ A ∨ B ”(¬ 表示非,∨ 表示或)。 Therefore, we can translate the statement "¬ A ∨ B " back to " behavior != 'bad'
OR 'treat != 'lollies'
".因此,我们可以将语句“¬ A ∨ B ”翻译回“ behavior != 'bad'
OR 'treat != 'lollies'
”。
In terms of SQL, we can write this as:在 SQL 方面,我们可以这样写:
CHECK (behaviour <> 'bad' OR treat <> 'lollies')
This is equivalent to:这相当于:
CHECK (NOT (behaviour = 'bad' AND treat = 'lollies'))
Try this试试这个
create table children (
childname VARCHAR2(50), behaviour VARCHAR2(50),treats VARCHAR2(50),
constraint behave_treat check (behaviour = 'bad' AND treats != 'lollies')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.