我正在使用Access database
,我想将Check Constraint
保存为查询。这在Access
中是否可能?
无论如何,这是我的查询:
ALTER TABLE LEVERANCIER
ADD CONSTRAINT chk_postcode CHECK(
NOT EXISTS(
SELECT levnr, postcode
FROM LEVERANCIER
WHERE Left(postcode, 4) = 5050 OR Woonplaats = "Amsterdam"));
它在AnySQL Maestro中有效,但它在Access中不起作用。
答案 0 :(得分:1)
Access数据库引擎支持CHECK约束,但无法从Access中的查询设计器执行创建它们的DDL。必须使用VBA代码和ADO连接创建它们,如下所示:
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