在 Access 中检查约束
Check Constraints in Access
我正在处理 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 中无效..
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
我正在处理 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 中无效..
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