How to set a validation rule on a field in Access

2019-05-17 07:53发布

问题:

I am using MS Access 2016 (Office 365) and I am currently facing an issue. Below is an example demonstrating this issue.

Here I created a Table named as NodeFamilyLink, which consists of two fields: NodeID and FamilyID as shown below.

Now the NodeID's are obtained from another table NodeData, which consists of 3 fields: NodeID, NodeName and ParentID. In this table, all the nodes are defined initially as shown in the below image.

Now, what I want is while entering a number inside the NodeID column of the NodeFamilyLink table, if I enter a NodeID value which is not included in the ParentID column of the NodeData table, then that NodeID value will be considered as a valid one and rest other values will considered as invalid ones. So, I want to apply a validation rule on the NodeID field of the NodeFamilyLink table using a query. But the problem is that I didn't find an option to set the validation rule using query in ACCESS (as shown in the below image).

Although I can easily achieve the same by programming with the OLE-DB API (in VB.NET), but I want to know if there is any method with the help of which I can accomplish my task without writing any code for it. Please help.

回答1:

I think you might be looking for the DLookup() function... This allows you to do a query type lookup in another table without writing code. How do I go about using DLookup in a validation rule of a text box on a form in access

But an important distinction here is that the DLookup() function is only available in the validation context at the form level, not the table level.

Depending on exactly where you are wanting to use the validation, this may give you a workable option for using query type lookups as part of your validation rules without writing code.



回答2:

You're probably looking for a CHECK constraint:

ALTER TABLE NodeFamilyLink
ADD CONSTRAINT myConstraintName
CHECK (
   NOT EXISTS( SELECT 1 FROM NodeFamilyLink INNER JOIN NodeData ON NodeData.ParentID = NodeFamilyLink.NodeID)
)

Note that these can only be added through ADO (by using CurrentProject.Connection.Execute), or when the database is using ANSI-92 compatible syntax.