How to set a validation rule on a field in Access

2019-05-17 07:20发布

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.

NodeFamilyLinkTable

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.

NodeDataTable

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).

ExpressionBuilder

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.

2条回答
萌系小妹纸
2楼-- · 2019-05-17 07:57

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.

Not available at table level

Available at form 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.

查看更多
We Are One
3楼-- · 2019-05-17 08:09

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.

查看更多
登录 后发表回答