问题
Using a MS Acess 2007 database accessed by vb.net application I have two existing table
Members
-------
ID name bandID
-----------------------
0 Pierre 1
1 Chart 3
2 John 3
3 Dave 2
Bands
-----
ID bandName
----------------
1 Band a
2 Band b
3 Band c
I want to add an cascade to null constraint to the relation between members.bandId and bands.ID
This is what I have
ALTER TABLE members ADD CONSTRAINT membresBands_FK
FOREIGN KEY (bandID) REFERENCE Bands(ID) ON DELETE CASCADE SET NULL
But I get this error message:
Syntax error in CONSTRAINT clause
From msdn I found
CREATE TABLE Orders
(OrderId INTEGER PRIMARY KEY,
CustId INTEGER,
OrderNotes NCHAR VARYING (255),
CONSTRAINT FKOrdersCustId FOREIGN KEY (CustId)
REFERENCES Customers ON UPDATE SET NULL ON DELETE SET NULL
Is it possible to alter a table in MS Access to set relationship to cascade to null?
Thank you!
回答1:
You can create this kind of constraint in Access, but only through the Jet OLE DB Provider and ADO. For example, with the database in Access, you could create the constraint by running the following VBA code:
CurrentProject.Connection.Execute "ALTER TABLE membres ADD CONSTRAINT membresBands_FK FOREIGN KEY (bandID) REFERENCES bands(ID) ON DELETE SET NULL"
回答2:
I had to wait eight hours to post this...
Using a visual basic module
'Define the bit value for the relation Attributes.
Public Const dbRelationCascadeNull As Long = &H2000
Public Function MakeRel()
'Purpose: Create a Cascade-to-Null relation using DAO.
Dim db As DAO.Database
Dim rel As DAO.Relation
Dim fld As DAO.Field
Set db = CurrentDb()
'Arguments for CreateRelation(): any unique name, primary table, related table, attributes.
Set rel = db.CreateRelation("membre_bands", "bands", "membres", dbRelationCascadeNull)
Set fld = rel.CreateField("ID") 'The field from the primary table.
fld.ForeignName = "band" 'Matching field from the related table.
rel.Fields.Append fld 'Add the field to the relation's Fields collection.
db.Relations.Append rel 'Add the relation to the database.
'Report and clean up.
Debug.Print rel.Attributes
Set db = Nothing
End Function
then call the MakeRel function
function found on http://allenbrowne.com/ser-64.html
回答3:
AFAIK, there is NO Cascade to Null
in Access. Only Cascade Delete
and Cascade Update
.
回答4:
Options for cascading effects in various DBMS are:
ON DELETE SET NULL
ON DELETE CASCADE
ON DELETE RESTRICT
ON DELETE NO ACTION
I think MS-Access has the first two. So, it should be:
ON DELETE SET NULL
回答5:
The docs for Access say that it supports the following referential triggered actions:
ON DELETE CASCADE
ON UPDATE CASCADE
ON DELETE SET NULL
ON UPDATE SET NULL
...However, in practice it only supports the first three i.e. does not support ON UPDATE SET NULL
. To further clarify, the engine does not support the ON UPDATE SET NULL
referential triggered action at all i.e. not just the DDL syntax.
来源:https://stackoverflow.com/questions/10386763/ms-access-set-cascade-to-null-constraint-to-existing-table