在Access数据库中控制重复密钥

时间:2019-05-02 10:11:20

标签: ms-access vb6 primary-key

我对Access DB和VB6有问题。

我有一个制作发票的程序,发票编号是唯一的密钥。 问题是两个人同时在介绍发票的网络中工作。 我需要检查每个人输入的发票编号是否不存在,以免重复。

Private Sub GuardarFactura()

If InvoiceNumberExist Then
    MessageBox UserControl.hWnd, "Invoice number duplicate", "Control de errores", vbExclamation
    Exit Sub
End If

On Error GoTo ErrorGuardar

Dim HayTrans As Boolean

AreaDeTrabajo.BeginTrans
HayTrans = True

Screen.MousePointer = vbHourglass

With recFrasEmi
    .AddNew
    !Numero = teInvoiceNumber
    !Fecha = CDate(teFecha)
    !TotalEuros = Format(CDbl(teTotal), FormatoImporte)
    .Update
    .Move 0, .LastModified
End With

AreaDeTrabajo.CommitTrans
HayTrans = False

DoEvents

Screen.MousePointer = vbDefault

Exit Sub

ErrorGuardar:

    If HayTrans Then AreaDeTrabajo.Rollback
    Screen.MousePointer = vbDefault

    MessageBox UserControl.hWnd, Err.Number & ": " & Err.Description, "Control de errores", vbExclamation

End Sub

function InvoiceNumberExist

    dim RS as recordset

    Sql "Select * From Facturas Where Numero='" & teInvoiceNumber & "'"

    Set RS = BD.OpenRecordset(Sql)
    If Not (RS.EOF And RS.BOF) Then
        InvoiceNumberExist=true
    else
        InvoiceNumberExist=false
    End If

end function

如果用户同时工作,InvoiceNumberExist并不总是工作, 我知道我可以使用“ if Err = 3022 then ....”,但是有可能在错误之前找到重复的数字吗?

谢谢

1 个答案:

答案 0 :(得分:0)

谢谢,然后我认为唯一的解决方案是对错误goto使用:

Private Sub GuardarFactura()

On Error GoTo ErrorGuardar

Dim HayTrans As Boolean

AreaDeTrabajo.BeginTrans
HayTrans = True

Screen.MousePointer = vbHourglass

With recFrasEmi
.AddNew
!Numero = teInvoiceNumber
!Fecha = CDate(teFecha)
!TotalEuros = Format(CDbl(teTotal), FormatoImporte)
.Update
.Move 0, .LastModified
End With

AreaDeTrabajo.CommitTrans
HayTrans = False

DoEvents

Screen.MousePointer = vbDefault

Exit Sub

ErrorGuardar:

If HayTrans Then AreaDeTrabajo.Rollback
Screen.MousePointer = vbDefault

If Err=3022 Then
   MessageBox UserControl.hWnd, "Invoice number duplicate", "Control de errores", vbExclamation
Else
   MessageBox UserControl.hWnd, Err.Number & ": " & Err.Description, "Control de errores", vbExclamation
End If

End Sub