在提交新记录之前检查记录是否存在

时间:2015-01-26 14:08:43

标签: sql vba access-vba

我目前有一个函数,它在Access 2010中使用SQL语句将记录插入到表中。

Sub btnSubmit_Click()

dim strSQL as string

strSQL="INSERT INTO tblMaster (PeriodID,ClassID,ChildID,SubjectID,LevelID) VALUES (" & cboPeriod & "," & cboClass & "," & cboName & "," & tbSubject1 & "," & cboLevel1 & ")"

CurrentDB.Execute strSQL
End Sub

我首先要做的是检查'tblMaster'是否已经有相同的记录。

我将如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

我想象在最坏的情况下会有一些唯一的标识符;以下应该有效。

Sub btnSubmit_Click()
    Dim strSQL as string

    strSQL = "INSERT INTO tblMaster (PeriodID, ClassID, ChildID, SubjectID, LevelID) VALUES (" & _
                cboPeriod & ", " & cboClass & ", " & cboName & ", " & tbSubject1 & ", " & cboLevel1 & ")"

    If DCount("*", "tblMaster", "PeriodID = " & cboPeriod & " AND " & _
                                "ClassID = " & cboClass & " AND " & _
                                "ChildID = " & cboName & " AND " & _
                                "SubjectID = " & tbSubject1 & " AND " & _
                                "LevelID = " & cboLevel1) = 0 Then
        CurrentDB.Execute strSQL
    Else
        MsgBox "A Record already exists for this information.", vbOKOnly, "No Records Added."
    End If
End Sub

答案 1 :(得分:0)

您可以使用其他选择语句检查该记录是否存在。