Check Constraints in Access

北慕城南 提交于 2019-11-27 08:18:30

问题


I'm working on an Access database, and I want to save a Check Constraint as a query. Is that even possible in Access?? Anyhow, this is my Query:

ALTER TABLE LEVERANCIER
ADD CONSTRAINT chk_postcode CHECK(
NOT EXISTS(
SELECT levnr, postcode
FROM LEVERANCIER
WHERE Left(postcode, 4) = 5050 OR Woonplaats = "Amsterdam"));

It does work in AnySQL Maestro, but it doesn't work in Access..


回答1:


The Access Database Engine does support CHECK constraints, but the DDL to create them cannot be executed from the Query Designer in Access. They must be created using VBA code and an ADO connection, like so:

Option Compare Database
Option Explicit

Public Sub AddCheckConstraint()
    Dim strSql As String
    strSql = _
            "ALTER TABLE LEVERANCIER" & vbNewLine & _
            vbTab & "DROP CONSTRAINT chk_postcode;"
    On Error Resume Next
    CurrentProject.Connection.Execute strSql
    On Error GoTo 0
    strSql = _
            "ALTER TABLE LEVERANCIER" & vbNewLine & _
            vbTab & "ADD CONSTRAINT chk_postcode" & vbNewLine & _
            vbTab & "CHECK (" & vbNewLine & _
            vbTab & vbTab & "NOT EXISTS (" & vbNewLine & _
            vbTab & vbTab & vbTab & "SELECT levnr, postcode " & vbNewLine & _
            vbTab & vbTab & vbTab & "FROM LEVERANCIER " & vbNewLine & _
            vbTab & vbTab & vbTab & "WHERE Left(postcode, 4) = '5050' OR Woonplaats = 'Amsterdam' " & vbNewLine & _
            vbTab & vbTab & ")" & vbNewLine & _
            vbTab & ");"
    CurrentProject.Connection.Execute strSql
End Sub


来源:https://stackoverflow.com/questions/27980784/check-constraints-in-access

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