如何防止重複值不插入表中。我創建了一個INSERT,UPDATE和DELETE的代碼,我想顯示一個MsgBox,它有一個重複的值並取消它。謝謝。下面你的代碼:訪問VBA /防止重複值
Private Sub Command12_Click()
If Me.emID.Tag & "" = "" Then
If (IsNull(Me.emID) Or (Me.emID = "") Or IsNull(Me.emFirst) Or (Me.emFirst = "") Or IsNull(Me.emLast) Or (Me.emLast = "")) Then
Me.emID.BorderColor = vbRed
Me.emFirst.BorderColor = vbRed
Me.emLast.BorderColor = vbRed
MsgBox "Please fill required fields", vbInformation, "Information"
Exit Sub
End If
CurrentDb.Execute "INSERT INTO tblEmployees(emID, first, last, gender, phone, mobphone, city, state, zip, adress, email, comment)" & _
"VALUES ('" & Me.emID & "', '" & Me.emFirst & "', '" & Me.emLast & "', '" & Me.emGender & "', '" & Me.emPhone & "', '" & Me.emMob & "', '" & Me.emCity & "', '" & Me.emState & "', '" & Me.emZip & "', '" & Me.emAdress & "', '" & Me.emEmail & "', '" & Me.emComment & "')"
MsgBox "Record Added", vbInformation, "information"
Else
CurrentDb.Execute "UPDATE tblEmployees " & _
"SET emiD =" & Me.emID & _
", first ='" & Me.emFirst & "'" & _
", last = '" & Me.emLast & "'" & _
", gender ='" & Me.emGender & "'" & _
", phone = '" & Me.emPhone & "'" & _
", mobphone ='" & Me.emMob & "'" & _
", city ='" & Me.emCity & "'" & _
", state ='" & Me.emState & "'" & _
", zip ='" & Me.emZip & "'" & _
", adress ='" & Me.emAdress & "'" & _
", email ='" & Me.emEmail & "'" & _
", comment ='" & Me.emComment & "'" & _
"WHERE emID =" & Me.emID.Tag
MsgBox "Updated!", vbInformation, "Information"
End If
Me.tblEmployees_subform.Form.Requery
End Sub
非常簡單:當一個新值插入時,首先儘量選擇它。如果選擇的結果不爲空,則表示它是重複的,並且不允許其餘代碼運行。注意:如果您的數據可能存在風險,您可能會遇到[SQL注入](http://www.w3schools.com/sql/sql_injection.asp),請考慮使用參數化SQL(我不知道AdoDB的VBA提供雖然,也許嘗試清除插入自己,如果沒有)。 –
您可以首先查詢數據庫,以查看其他記錄是否已與您要插入/更新的內容匹配。或者在表中添加約束條件,不允許在定義它們時使用重複項。 –