Conditional SQLite check constraint?

血红的双手。 提交于 2019-12-18 12:09:10

问题


I have a table defined by the following SQL:

CREATE TABLE test (
  id       integer PRIMARY KEY NOT NULL UNIQUE,
  status   text NOT NULL,
  enddate  date,
  /* Checks */
  CHECK (status IN ("Current", "Complete"))
);

I'd like to add a constraint that requires enddate to be non-null if the status is "Complete".

Is this possible? I am using SQLite v3.6.16.


回答1:


How about:

CHECK (status = "Current" or (status = "Complete" and enddate is not null))



回答2:


CREATE TABLE test (
  id       integer PRIMARY KEY,
  status   text NOT NULL CHECK (status IN ('Current', 'Complete')),
  enddate  date NOT NULL
);

This will work in SQLite, with the CHECK constraint written inline. I changed double quotes to apostrophes so it can be used in PHP.




回答3:


There's nothing stopping you from having multiple CHECK constraints on a single table. IMO the simplest and most easily expandable solution:

CHECK (status IN ("Current", "Complete"))
CHECK (status <> "Complete" OR enddate IS NOT NULL)

This uses the fact that if A then B is logically equivalent to either not A or B.



来源:https://stackoverflow.com/questions/2615477/conditional-sqlite-check-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!