Quantcast
Channel: VBForums
Viewing all articles
Browse latest Browse all 15785

VS 2010 How to ignore saving records that can make duplicate before inserting to database?

$
0
0
I have to import or copy the records from one database to another. My problem is it continuously insert records even if they are already existing. I want to control inserting duplicate records. I want them to be ignored and only those records that are not existing in database will be inserted. Any suggestion or modification in my code is highly appreciated. Thank you.

This is my initial code:

Code:

Dim con1 As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= database1.accdb")
    Dim con2 As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= database2.accdb")

    con2.Open()
    Dim CompQuery As String = "SELECT COUNT(*) FROM sampletable WHERE FirstName = @FirstName AND LastName = @LastName"
    Dim compCommand As OleDbCommand = New OleDbCommand(CompQuery, con2)
    compCommand.Parameters.AddWithValue("@FirstName", "FirstName")
    compCommand.Parameters.AddWithValue("@LastName", "LastName")
   
    If Convert.ToInt32(compCommand.ExecuteScalar()) > 0 Then
    'ignoring duplicate entries msgbox("Some records fail to save because it would create duplicate     
    entries!")
        Exit Sub
    Else

        'Create the data adapter with a SelectCommand using the first connection.
        Dim da As New OleDb.OleDbDataAdapter("SELECT FirstName, LastName FROM table1 ", con1)
        'Add the InsertCommand with the second connection.
        da.InsertCommand = New OleDb.OleDbCommand("INSERT INTO sampletable (FirstName, LastName) VALUES (@FirstName, @LastName)", con2)
        'Add the insert parameters.                                                                                               
        da.InsertCommand.Parameters.Add("@FirstName", OleDb.OleDbType.VarChar, 50, "FirstName")
        da.InsertCommand.Parameters.Add("@LastName", OleDb.OleDbType.VarChar, 50, "LastName")
                  'Keep the records in a state where they can be inserted into the destination table.
        da.AcceptChangesDuringFill = False
        Dim dt As New DataTable
        'Get the data from the source database.
        da.Fill(dt)
        'Save the data to the destination database.
        da.Update(dt)
        MsgBox("Data Added!")

        con1.Dispose()
        con2.Dispose()

    End If


Viewing all articles
Browse latest Browse all 15785

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>