Inserting data to Access Duplicate Data Error
Asked Answered
D

1

8

I have wrote some vbscript that updates all new fields in one access database from a table in another database however I am having problems with duplicate primary keys.

I can't change the structure of the database so I can't remove the primary keys however ideally I would like it to auto populate the primary key. Here is my table structure (their are two tables)

Table 'Order':

Order Sequence Number   About 20 more rows of data that do not have to be unique
a primary key e.g 2     other data

Table 'OrderDetail':

OrderDetail     OrderSequence       Some other rows that don't need to be unique
a primary key   the key from Order  some other data

My first problem is having the primary key for both tables auto populate so they are unique, then my second problem is matching the two rows that are being added and if the primary key changes on 'Order' table for 'Order Sequence Number' update it on 'OrderSequence' in the table 'OrderDetail'.

Here is my vbscript that works copying values if they are unique:

Public Function dhupdate1()

    'Temp field
    Dim fField As Field
    Dim bCopy As Boolean

    'Open source database
    Dim dSource As Database
    Set dSource = CurrentDb

    'Open dest database
    Dim dDest As Database
    Set dDest = DAO.OpenDatabase("\\BMCDONALD-PC\SellerDeck 2013\Sites\New_Site\ActinicCatalog.mdb")

    'Open source recordset
    Dim rSource As Recordset
    Set rSource = dSource.OpenRecordset("OrderDetail", dbOpenForwardOnly)

    'Open dest recordset
    Dim rDest As Recordset
    Set rDest = dDest.OpenRecordset("OrderDetail", dbOpenDynaset)

    'Loop through source recordset
    While Not rSource.EOF

        'Reset copy flag
        bCopy = False

        'Look for record in dest recordset
        rDest.FindFirst "OrderDetailID = " & rSource.Fields("OrderDetailID") & ""

        If rDest.NoMatch Then
           'If not found, copy record
            rDest.AddNew
            bCopy = True
        End If

        'If copy flag is set, copy record
        If bCopy Then
            For Each fField In rSource.Fields
                rDest.Fields(fField.Name) = rSource.Fields(fField.Name)
            Next fField
            Set fField = Nothing
            rDest.Update
        End If

        'Next source record
        rSource.MoveNext
    Wend

    'Close dest recordset
    rDest.Close
    Set rDest = Nothing

    'Close source recordset
    rSource.Close
    Set rSource = Nothing

    'Close dest database
    dDest.Close
    Set dDest = Nothing

    'Close source database
    dSource.Close
    Set dSource = Nothing

End Function
Public Function dhupdate2()

   'Temp field
    Dim fField As Field
    Dim bCopy As Boolean

    'Open source database
    Dim dSource As Database
    Set dSource = CurrentDb

    'Open dest database
    Dim dDest As Database
    Set dDest = DAO.OpenDatabase("\\BMCDONALD-PC\SellerDeck 2013\Sites\New_Site\ActinicCatalog.mdb")

    'Open source recordset
    Dim rSource As Recordset
    Set rSource = dSource.OpenRecordset("Order", dbOpenForwardOnly)

    'Open dest recordset
    Dim rDest As Recordset
    Set rDest = dDest.OpenRecordset("Order", dbOpenDynaset)

    'Loop through source recordset
    While Not rSource.EOF

        'Reset copy flag
        bCopy = False

        'Look for record in dest recordset
        rDest.FindFirst "[Order Number] = '" & rSource.Fields("Order Number") & "'"

        If rDest.NoMatch Then
           'If not found, copy record
            rDest.AddNew
            bCopy = True
        End If

        'If copy flag is set, copy record - ignore errors
        If bCopy Then
            For Each fField In rSource.Fields
                On Error Resume Next
                rDest.Fields(fField.Name) = rSource.Fields(fField.Name)
                On Error GoTo 0
            Next fField
            Set fField = Nothing
            rDest.Update
        End If

        'Next source record
        rSource.MoveNext
    Wend

    'Close dest recordset
    rDest.Close
    Set rDest = Nothing

    'Close source recordset
    rSource.Close
    Set rSource = Nothing

    'Close dest database
    dDest.Close
    Set dDest = Nothing

    'Close source database
    dSource.Close
    Set dSource = Nothing

End Function

I have been reading about auto populating if its not unique however I am getting confused where I need these two functions to get both rows for one order and changing both numbers for the order sequence. I am still fairly new to VB so any help is really appreciated.

Thanks, Simon

Dorcy answered 6/12, 2013 at 11:11 Comment(2)
Are the primary key fields AutoNumber fields?Gouda
They are AutoNumber and have removed the tagsDorcy
G
4

Instead of copying all records for each table from "source" to "dest" in one shot, you could loop through the parent records, copying one parent record and its related child records for each iteration. That is:

  • copy parent record 1
  • copy child records for parent record 1
  • copy parent record 2
  • copy child records for parent record 2
  • ...and so on.

The following sample code may prove helpful:

Option Compare Database
Option Explicit

Public Function CopyOrders()
    Dim dSource As DAO.Database, rSourceOrder As DAO.Recordset, rSourceDetail As DAO.Recordset
    Dim dDest As DAO.Database, rDestOrder As DAO.Recordset, rDestDetail As DAO.Recordset
    Dim fld As DAO.Field, newDestOrderID As Long

    Set dSource = CurrentDb
    Set rSourceOrder = dSource.OpenRecordset("Order", dbOpenSnapshot)

    Set dDest = DAO.OpenDatabase("C:\__tmp\OrderCopy\dest.mdb")
    Set rDestOrder = dDest.OpenRecordset("Order", dbOpenDynaset)
    Set rDestDetail = dDest.OpenRecordset("OrderDetail", dbOpenDynaset)

    Do Until rSourceOrder.EOF
        ' copy one Order record
        rDestOrder.AddNew
        For Each fld In rDestOrder.Fields
            If fld.Name <> "OrderID" Then
                rDestOrder.Fields(fld.Name).Value = rSourceOrder.Fields(fld.Name).Value
            End If
        Next
        newDestOrderID = rDestOrder.Fields("OrderID").Value
        rDestOrder.Update  ' commit parent record so child records can be added

        ' now copy all related OrderDetail records
        Set rSourceDetail = dSource.OpenRecordset( _
                "SELECT * FROM OrderDetail " & _
                "WHERE OrderID=" & rSourceOrder!OrderID, _
                dbOpenSnapshot)
        Do Until rSourceDetail.EOF
            rDestDetail.AddNew
            ' use new AutoNumber from parent table (rDestOrder) as foreign key
            rDestDetail.Fields("OrderID").Value = newDestOrderID
            For Each fld In rDestDetail.Fields
                Select Case fld.Name
                    Case "OrderDetailID", "OrderID"
                        ' do nothing
                    Case Else
                        rDestDetail.Fields(fld.Name).Value = rSourceDetail.Fields(fld.Name).Value
                End Select
            Next
            rDestDetail.Update
            rSourceDetail.MoveNext
        Loop
        rSourceDetail.Close
        Set rSourceDetail = Nothing
        rSourceOrder.MoveNext
    Loop
    rDestDetail.Close
    Set rDestDetail = Nothing
    rDestOrder.Close
    Set rDestOrder = Nothing
    rSourceOrder.Close
    Set rSourceOrder = Nothing
    dDest.Close
    Set dDest = Nothing
    Set dSource = Nothing
End Function

edit re: new information

The primary key in the child table is not an AutoNumber, so you're right that you'll just have to "roll your own". Try the following (changes marked as <v1.1>):

Public Function CopyOrders()
    Dim dSource As DAO.Database, rSourceOrder As DAO.Recordset, rSourceDetail As DAO.Recordset
    Dim dDest As DAO.Database, rDestOrder As DAO.Recordset, rDestDetail As DAO.Recordset
    Dim fld As DAO.Field, newDestOrderID As Long
    Dim nextDestOrderDetailID As Long  ' <v1.1/>

    Set dSource = CurrentDb
    Set rSourceOrder = dSource.OpenRecordset("Order", dbOpenSnapshot)

    Set dDest = DAO.OpenDatabase("C:\Users\ANON\Documents\OrderMove\dh\ActinicCatalog.mdb")
    Set rDestOrder = dDest.OpenRecordset("Order", dbOpenDynaset)
    ' <v1.1>
    Set rDestDetail = dDest.OpenRecordset("SELECT Max(OrderDetailID) AS maxODI FROM OrderDetail", dbOpenSnapshot)
    nextDestOrderDetailID = Nz(rDestDetail!maxODI, 0) + 1
    rDestDetail.Close
    ' </v1.1>
    Set rDestDetail = dDest.OpenRecordset("OrderDetail", dbOpenDynaset)

    Do Until rSourceOrder.EOF
        ' copy one Order record
        rDestOrder.AddNew
        For Each fld In rDestOrder.Fields
            If fld.Name <> "Order Sequence Number" Then
                rDestOrder.Fields(fld.Name).Value = rSourceOrder.Fields(fld.Name).Value
            End If
        Next
        newDestOrderID = rDestOrder.Fields("Order Sequence Number").Value
        rDestOrder.Update  ' commit parent record so child records can be added

        ' now copy all related OrderDetail records
        Set rSourceDetail = dSource.OpenRecordset( _
                "SELECT * FROM OrderDetail " & _
                "WHERE OrderSequenceNumber=" & rSourceOrder![Order Sequence Number], _
                dbOpenSnapshot)
        Do Until rSourceDetail.EOF
            rDestDetail.AddNew
            ' use new AutoNumber from parent table (rDestOrder) as foreign key
            rDestDetail.Fields("OrderSequenceNumber").Value = newDestOrderID
            ' <v1.1>
            rDestDetail.Fields("OrderDetailID").Value = nextDestOrderDetailID
            nextDestOrderDetailID = nextDestOrderDetailID + 1
            ' </v1.1>
            For Each fld In rDestDetail.Fields
                'Select Case fld.Name
                 '   Case "OrderDetailID", "OrderSequenceNumber"
                        ' do nothing
                '    Case Else
                '        rDestDetail.Fields(fld.Name).Value = rSourceDetail.Fields(fld.Name).Value
                'End Select
                If fld.Name <> "OrderDetailID" Then
                    If fld.Name <> "OrderSequenceNumber" Then
                        rDestDetail.Fields(fld.Name).Value = rSourceDetail.Fields(fld.Name).Value
                    End If
                End If
            Next
            rDestDetail.Update
            rSourceDetail.MoveNext
        Loop
        rSourceDetail.Close
        Set rSourceDetail = Nothing
        rSourceOrder.MoveNext
    Loop
    rDestDetail.Close
    Set rDestDetail = Nothing
    rDestOrder.Close
    Set rDestOrder = Nothing
    rSourceOrder.Close
    Set rSourceOrder = Nothing
    dDest.Close
    Set dDest = Nothing
    Set dSource = Nothing
End Function
Gouda answered 9/12, 2013 at 10:53 Comment(11)
@SimonStaton You can download a copy of the sample files here. The module code is in "source.mdb".Gouda
This looks great, is a shame I can't increase the bounty for you! I am just testing it and getting error 3265: Item not found in this collection. any ideas?Dorcy
Okay fixed the error just updated the OrderID to my field Order Sequence Number however I'm still getting the original error 3022 on the rDestOrder.UpdateDorcy
It looks like it is still doing the original edit to the database by moving the first "order" values over but getting stuck trying to add a duplicate, let me make sure there are no other autonumbers on the table.Dorcy
@SimonStaton Keep plugging away at it. The key things to bear in mind are: (1) Whenever a new record is created (via AddNew) its AutoNumber key value is guaranteed unique for that table but it is also something we cannot (or at least "should not try to") overwrite. That's why the loops to copy over the other fields specifically exclude the primary keys ([OrderID] and [OrderDetailID] in my example). (2) When copying over the child records we need to use the newly-created parent ID value (newDestOrderID) as the foreign key ([OrderID] in the child table).Gouda
I have managed to get it working to an extent, however upon updating OrderDetail where we have Case "OrderDetailID", "OrderSequenceNumber" and we are doing nothing with our index key, it is giving me this error on update: 3058: Index or primary key cannot contain a Null value. I am fairly new to vb but I imagine its because the database structure on OrderDetail is not using an autonumber?Dorcy
Am just trying to find some posts on here about getting the last row on the new database and adding 1 to get the value for the new primary key that is not auto number. If you have any suggestions would be hugely appreciated! :)Dorcy
@SimonStaton If you can, create a new file with just the two actual tables in it (each one with 1 or 2 dummy records, if possible), upload the result to a site like wikisend.com, and post the link here. It sounds like your tables structures might be rather different than the ones in my example.Gouda
I have just uplaoded it here: www34.zippyshare.com/v/90025236/file.html the destination database is in the dh folder and the source is the database outside this folder, I think I have remapped it all okay the only problem is adding the primary key that has no autonumber, could I not grab the max number in this column and add one maybe?Dorcy
I am so close, I am still unable to find any posts online about getting a primary key that is not auto number. It makes sence grabbing the last number and adding one but I have no idea how to :(Dorcy
Awesome thanks Gord this seems to have done the job! :) So it was just the fields and the second primary key that I was not doing right. Thank you very much for the help.Dorcy

© 2022 - 2024 — McMap. All rights reserved.