在MS Access VBA中创建外键

问题描述 投票:0回答:3

我有表tbl0和表tbl1。 tbl0有一个由我像这样创建的字段“ Ticker”制成的主键:

Sub CreatPrimaryKey()
Dim db As Database
Set db = CurrentDb
db.Execute "CREATE INDEX TickerID ON tbl0 (Ticker) WITH PRIMARY;"
db.Close
End Sub

...效果很好。

我通过使用此命令确认我拥有主键:

Sub GetPrimaryKeyField()
Call PrimKey("tbl0")
End Sub

Public Sub PrimKey(tblName As String)
'get primary key of tabel
'how to use: Call PrimKey("tbl_DatedModel_2015_0702_0")
'http://bytes.com/topic/access/answers/679509-finding-primary-key-using-vba
'*******************************************
'Purpose: Programatically determine a
' table's primary key
'Coded by: raskew
'Inputs: from Northwind's debug window:
' Call PrimKey("Products")
'Output: "ProductID"
'*******************************************

Dim db As Database
Dim td As TableDef
Dim idxLoop As Index

Set db = CurrentDb
Set td = db.TableDefs(tblName)
For Each idxLoop In td.Indexes
If idxLoop.Primary = True Then
Debug.Print Mid(idxLoop.Fields, 2)
Exit For
End If
Next idxLoop

db.Close
Set db = Nothing
End Sub

立即窗口打印“股票行情指示器”。我不确定“ TickerID”发生了什么,但是无论如何。我得到一个PK。然后,我尝试通过执行以下操作在tbl0和tbl1之间创建外键关系:

Sub CreateForeignKey()Dim db As Database
Set db = CurrentDb

db.Execute "ALTER TABLE tbl1 " _
        & "ADD CONSTRAINT fk_tbl1_tbl0 " _
        & "FOREIGN KEY (Ticker) REFERENCES tbl0 (Ticker);"

    db.Close
End Sub

[当我运行上面的子程序时出现错误:“索引或关系的定义中的无效字段定义” Ticker“”

更新:使这个问题与众不同的原因是我遇到的问题的一部分是,当我更改表时,我需要在两个表中都具有相同的字段。

sql vba ms-access access-vba ms-access-2013
3个回答
1
投票
您的外键SQL应该是:

ALTER TABLE tbl1 ADD CONSTRAINT fk_tbl1_tbl0 FOREIGN KEY (Ticker) REFERENCES tbl0 (Ticker);

这假设您在tbl1中有一个名为“ Ticker”的字段,与tbl0.Ticker的类型相同。

第二行表示您要创建的外键字段引用了另一个表中的相关键字段。像这样读取:我正在更改的表(tbl1)中的外键“ Ticker”引用相关表“ tbl0”中的主键“ Ticker”。

我使用此例程,您可能会有所帮助。它确实做了一些假设:1)主键始终被命名为{table_name} +“ Id”,并且2)外键通常被命名为同一事物。 (这两种都是常见做法,我认为这是可取的)。

Public Function CreateForeignKey( _ db As DAO.Database, _ ByVal sTable As String, _ ByVal sPrimaryTable As String, _ Optional ByVal sField As String) As Boolean Dim sSQL As String Dim sSuffix As String On Error GoTo EH If sField = "" Then sField = sPrimaryTable & "Id" Else sSuffix = "_" & sField End If sSQL = "ALTER TABLE [" & sTable & "]" _ & " ADD CONSTRAINT FK_" & sTable & "_" & sPrimaryTable & sSuffix _ & " FOREIGN KEY([" & sField & "])" _ & " REFERENCES [" & sPrimaryTable & "] ([" & sPrimaryTable & "Id]);" db.Execute sSQL, dbFailOnError CreateForeignKey = True Exit Function EH: MsgBox "Error " & Err.Number & vbCrLf _ & " (" & Err.Source & vbCrLf _ & " (" & Err.Description _ & ") in procedure CreateForeignKey of Module Database" End Function

参考:

CONSTRAINT Clause (Microsoft Access SQL)


0
投票
ALTER TABLE tbl1 ADD CONSTRAINT fk_tbl1_tbl0 FOREIGN KEY (TickerId) REFERENCES tbl0 (Ticker);

parentId是tickerID,而子代号是tickerID。


0
投票
Sub CreateTableJours() On Error Resume Next Application.CurrentDb.Execute "Drop Table [Jours];" '---------------'---------------' On Error GoTo onError Dim con As ADODB.Connection Set con = CurrentProject.Connection con.Execute "" _ & "CREATE TABLE [Jours](" _ & " [jcode] COUNTER" _ & ",[jdate] DATETIME" _ & ",[tid] INTEGER" _ & ",[cid] INTEGER" _ & ",[jdepense] MONEY" _ & ",[jjustificatif] CHAR" _ & ",CONSTRAINT [FK_Taches] FOREIGN KEY ([tid]) REFERENCES Personnes" _ & ",CONSTRAINT [FK_Chantiers] FOREIGN KEY ([cid]) REFERENCES Chantiers" _ & ",CONSTRAINT [PK_Jours] PRIMARY KEY ([jcode])" _ & ");" Set con = Nothing Exit Sub '---------------'---------------' onFail: myErrorLvl = 250 Set con = Nothing Exit Sub '---------------'---------------' onError: MsgBox Err.Description, , "Erreur(" & myErrorLvl & ") in " & "INIT.CreateTableJours" & "#" & Err.Number If myErrorLvl < 1 Then Resume onFail End Sub
© www.soinside.com 2019 - 2024. All rights reserved.