SQL Constraint/trigger - Is it possible to write a constraint that checks “when you Insert a record it must contain one of two fields”?

坚强是说给别人听的谎言 提交于 2019-12-11 01:15:25

问题


Is it possible to have a constraint/trigger on a record being entered that checks if the user has entered at least one of three fields (all of which can be null). For example, I have a database being used to track bugs and new features in other pieces of software. When a bug is discovered a Feature record is created which can have three foreign keys, discoveredID, fixedID or newFeatureID, all three can be null (because it could be a discovered bug, fixed bug or a new feature added to the software.) but the user must select at least one when entering data. I can control the input in an external program using my database but if someone else writes a program they may not put that check in place, so I want to stop them doing that and entering corrupt data.


回答1:


Using SQL Server, adding a Table level check constraint would suffice.

CREATE TABLE Bugs (
  discoveredID INTEGER
  , fixedID INTEGER 
  , newFeatureID INTEGER  
  )

ALTER TABLE Bugs ADD CONSTRAINT CKC_AtLeastOne CHECK (COALESCE(discoveredID, fixedID, newFeatureID) IS NOT NULL)

INSERT INTO Bugs VALUES (NULL, NULL, 1)
INSERT INTO Bugs VALUES (NULL, 1, NULL)
INSERT INTO Bugs VALUES (1, NULL, NULL)
INSERT INTO Bugs VALUES (NULL, NULL, NULL) -- Fails

DROP TABLE Bugs



回答2:


Reading your design got me thinking that maybe the problem could be in the table design more than the requirement to create a Constraint/Trigger.

For example, you mention that you can have 3 types of bug (discovered bug, fixed bug or a new feature)

Would it be possible to have a composite key of two fields which would be the bug type, with the assocaited ID field next to it.

So instead of: discoveredID, fixedID, newFeatureID

you'd have just: bugTypeID, BugID

With this change you could just concentrate on the bugTypeID being 1,2 or 3.



来源:https://stackoverflow.com/questions/3565159/sql-constraint-trigger-is-it-possible-to-write-a-constraint-that-checks-when

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