Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Append Records using VB and Where clause

Status
Not open for further replies.

tinkertek

MIS
Feb 7, 2006
15
US
Hi,

I have 2 similar Access 97 databases residing on 2 different servers. Let's call them \\Server1\DB1.mdb and \\Server2\DB2.mdb. Every day, I need to Append records to DB1.mdb using records from DB2.mdb, but don't want to create duplicates in DB1.mdb either. Any ideas how to code this using VB6 ? If not, what code in Access would work >

Thanks for any help !!!!

Tinkertek
 
I think this is pretty easy. First, cretae a recordset of the data you want to copy. Then open the table you want to append to as a recordset. Then all you have to do is loop through the first recordset adding records to the second as you go.

rs1.open "Select * from table1", conn
rs2.open "Table1", conn, , , adCmdTable

do until rs1.EOF
rs2.addnew
rs2.("Field1")=rs1.("Field1")
rs2.("Field2")=rs1.("Field1")
etc...
rs2.update
rs1.movenext
loop

rs1.close
rs2.close

This is something pretty close to what you need to do. Just not tooooo sure of the parameters used to open the recordsets.

If you need more help, just holler.
 
Sorry, the second line should read:

rs2.open "Table2", conn, adOpenDynamic, adLockOptomistic, adCmdTable
 
Thanks for the reply. I'll give it a try. I have to be careful not to add duplicate records to the appended table. I'm not that great using VB6, so I'll try to muddle through.

Tinkertek
 
Checking for duplicate records is easy enough. Just after you enter the do loop, before you perform the addnew method on rs2, open another recordset on the table you wish to add to, using the crieria you want to add. If the query returns an empty recordset, then you know the record you wish to add is not a duplicate.
 
I'm lost !!! I've got hours into this and can't make it work properly. Call me dense. What would the complete code be ? Thanks again for any help !
 
I haven't run this, but it should work. First, you need to set up two DSN's for your data sources. Next, start a new .exe project and add a command button to the form.

Code:
Option Explicit
Dim objCN1 As ADODB.Connection
Dim objCN2 As ADODB.Connection
Dim objRS1 As ADODB.Recordset
Dim objRS2 As ADODB.Recordset
Dim objRS3 As ADODB.Recordset

Private Sub Command1_Click()

Set objCN1 = New ADODB.Connection
Set objCN2 = New ADODB.Connection
Set objRS1 = New ADODB.Recordset
Set objRS2 = New ADODB.Recordset
Set objRS3 = New ADODB.Recordset

objCN1.Open "DSN=TEST"
objCN2.Open "DSN=TEST2"

objRS1.Open "SELECT * FROM TABLE1", objCN1, adOpenForwardOnly, adLockReadOnly  'Records to copy
objRS2.Open "TABLE2", objCN2, adOpenDynamic, adLockBatchOptimistic, adCmdTable  'Table to copy to

Do Until objRS1.EOF
    objRS3.Open "SELECT FIELD FROM TABLE2 WHERE KeyValue=" & objRS1("KeyValue"), objCN2, adOpenForwardOnly, adLockReadOnly  'Check for existing record
    If objRS3.EOF Then      'If EOF is TRUE, then the record does not exist
        objRS2.AddNew       'Add the record
        objRS2("Field1") = objRS1("Field1")
        objRS2("Field2") = objRS1("Field2")
        objRS2("Field3") = objRS1("Field3")
        objRS2("Field4") = objRS1("Field4")
        objRS2("Field5") = objRS1("Field5")
        objRS2.Update
    End If
    objRS1.MoveNext  'Move to next record to test and copy
    objRS3.Close  'Close the test recordset so we can open it again
Loop

objRS1.Close  'Cleanup
objRS2.Close
objCN1.Close
objCN2.Close
Set objRS1 = Nothing
Set objRS2 = Nothing
Set objRS3 = Nothing
Set objCN1 = Nothing
Set objCN2 = Nothing

End Sub

Private Sub Form_Load()



End Sub
 
Hi BJRollet,

Wow, you went through all that work for me ! That's awesome. I can't wait to try it out. I was way off.

I'll try it tommorrow or Friday and will let you know !

Thanks again !!!!
Tinkertek
 
There is a easier way:
If you can set a unique key on one of the fields in DB1 then do so. Otherwise, add one at run time, and after doing the append,(using ALTER TABLE, ADD CONSTRAINT, DROP CONSTRAINT), remove it (Using DAO in this example).

The use EXECUTE with something like :

myDb.EXECUTE "INSERT INTO myTable1
SELECT *
FROM myTable2 IN "D:\myPath\DB1.Mdb"

myDb being DB2

If you not use dbFailOnError constant for the EXECUTE options, the EXECUTE will add all unique fields with-out erroring out on duplicates.
 
Hi bjrollet,

I tried out the code and got this error after several seconds: Run-time error 2147217904 (80040e10) [Microsoft][ODBC Microsoft Access Driver] Too =
few parameters. Expected 1.
Source: Microsoft OLE DB Provider for ODBC Drivers

Here is the code as I compiled it:

Option Explicit
Dim objCN1 As ADODB.Connection
Dim objCN2 As ADODB.Connection
Dim objRS1 As ADODB.Recordset
Dim objRS2 As ADODB.Recordset
Dim objRS3 As ADODB.Recordset

Private Sub Command1_Click()

'Open connection to databases and recordsets, objCN1 = CT database, objCN2=Lawnt02 database
Set objCN1 = New ADODB.Connection
Set objCN2 = New ADODB.Connection
Set objRS1 = New ADODB.Recordset
Set objRS2 = New ADODB.Recordset
Set objRS3 = New ADODB.Recordset

objCN1.Open "DSN=Inventory_be_ct"
objCN2.Open "DSN=Inventory_be"

objRS1.Open "SELECT * FROM Assets", objCN1, adOpenForwardOnly, adLockReadOnly 'Records to copy
objRS2.Open "Assets", objCN2, adOpenDynamic, adLockBatchOptimistic, adCmdTable 'Table to copy to

Do Until objRS1.EOF
objRS3.Open "SELECT BarcodeNumber FROM Assets WHERE BarcodeNumber=" & objRS1("BarcodeNumber"), objCN2, adOpenForwardOnly, adLockReadOnly 'Check for existing record
If objRS3.EOF Then 'If EOF is TRUE, then the record does not exist
objRS2.AddNew 'Add the record
objRS2("BarcodeNumber") = objRS1("BarcodeNumber")
objRS2("AssetDescription") = objRS1("AssetDescription")
objRS2("Make") = objRS1("Make")
objRS2("Model") = objRS1("Model")
objRS2("SerialNumber") = objRS1("SerialNumber")
objRS2("Year Of Manufacture") = objRS1("Year of Manufacture")
objRS2("Options") = objRS1("Options")
objRS2("Firmware") = objRS1("Firmware")
objRS2("Status") = objRS1("Status")
objRS2("Repair History") = objRS1("Repair History")
objRS2("Region") = objRS1("Region")
objRS2("State") = objRS1("State")
objRS2("Site") = objRS1("Site")
objRS2("Comments") = objRS1("Comments")
objRS2("Rack") = objRS1("Rack")
objRS2("Row") = objRS1("Row")
objRS2("Slot") = objRS1("Slot")
objRS2("UpdatedBy") = objRS1("UpdatedBy")
objRS2("Channel") = objRS1("Channel")
objRS2("Address") = objRS1("Address")
objRS2("CalibrationDate") = objRS1("CalibrationDate")
objRS2("ReminderEmail") = objRS1("ReminderEmail")
objRS2.Update
End If
objRS1.MoveNext 'Move to next record to test and copy
objRS3.Close 'Close the test recordset so we can open it again
Loop

objRS1.Close 'Cleanup
objRS2.Close
objCN1.Close
objCN2.Close
Set objRS1 = Nothing
Set objRS2 = Nothing
Set objRS3 = Nothing
Set objCN1 = Nothing
Set objCN2 = Nothing

End Sub

Private Sub Form_Load()



End Sub

Thanks for any help !
 
ADO - appending data from one table in one database to another table in a 2nd database. The error

Sub test()

Dim cn As ADODB.Connection
Dim dbError As ADODB.Error

On Error GoTo ErrHandler

Set cn = New ADODB.Connection
cn.CursorLocation = adUseClient
cn.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=E:\DB1\myDB1.MDB;"

cn.Execute "INSERT INTO Customer " _
& "SELECT * " _
& "FROM Customer " _
& "IN C:\DB2\myDB2.MDB'"

ExitProceedure:
Exit Sub
ErrHandler:
For Each dbError In cn.Errors
If dbError.SQLState = 3022 Then
'Ignor duplicates - in order for this to work you
'need to set a unique key in the receiving DB


Else
MsgBox "Error: " & Err.Number - vbObjectError & vbCr & Err.Description
End If
Next dbError
Resume ExitProceedure
End Sub
 
Hi bjrollet,

I don't know which line is causing the error. You won't believe this, but I do not have VB at work, I only have it at home. So, I have to write the code at home, use the Package and Deployment Wizard, then email it to work, then go to work and run the setup file, then actually run it to test. It's insane, the good news is, my boss says he's trying to get me VB, we'll see.

Hi CCLINT,

I don't understand how you're code example works, as I am not at all familiar with ADO. I do not have a unique key in either database. Can I use just an autonumber field for this. And, if so, in which database ? Is your Test Sub() the complete code, I can just edit it to match my database names and paths ? If so, which References do I need in VB ?

Thankyou both for the help !!!!

 
Well, I set this whole thing up on my home computer and finally figured out the line that is causing the error, "Too few parameters expected 1"

objRS3.Open "SELECT BarcodeNumber FROM Assets WHERE BarcodeNumber=" & objRS1("BarcodeNumber"), objCN2, adOpenForwardOnly, adLockReadOnly 'Check for existing record

Any ideas ?

Thanks,
Tinkertek
 
Yes, you can use an auto number field - this should be unique. I have been using this with DAO for several years and changed it to ADO as above and it ran fine (I use this for combining two identical DBs, and the customers who have used this in the past have never had a problem. The only issue that you may have is when the databases are secured (like mine are). You will have to supply the passwords in the connection string and select statement.
Give it a try and a test - create 2 mdbs locally with one table each and an auto number field (create one and copy the other to a seperate path). The add the references for ADO and add the code above, changing the paths and mdb names....

Please be aware that if you are working with two Jet MDBs, then DAO will be the fastest....
 
Hi CCLINT,

I tried out your code and keep getting an error "syntax error in FROM clause". Here's the code:

Sub command1_click()

Dim cn As ADODB.Connection
Dim dbError As ADODB.Error

On Error GoTo ErrHandler

Set cn = New ADODB.Connection
cn.CursorLocation = adUseClient
cn.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ct\headend inventory_be_ct.mdb;"

cn.Execute "INSERT INTO Assets " _
& "SELECT * " _
& "FROM Assets " _
& "IN C:\my documents\headend inventory_be.mdb"

ExitProceedure:
Exit Sub
ErrHandler:
For Each dbError In cn.Errors
If dbError.SQLState = 3022 Then
'Ignor duplicates - in order for this to work you
'need to set a unique key in the receiving DB


Else
MsgBox "Error: " & Err.Number - vbObjectError & vbCr & Err.Description
End If
Next dbError
Resume ExitProceedure
End Sub



 
Your missing the single quotes around the database path and name....
(In my example I was missing one of them as well.
 
Hi CCLINT,

I fixed the single quote as you said and now it seems to function. However, it only copies the source database to itself, not to the destination database. It creates all kinds of duplicates in itself.

What a nightmare trying to get this project done !

I created a unique autonumber key in the destination database and created a autonumber key in the source. But, in the source, I didn't make it unique, but it probably is anyway. Tried various combinations of unique and not unique and it didn't seem to help. It seems I need to have the exact same fields in both databases though.

Maybe I should try to do this in DAO, rather than ADO ?

 
Make sure that the Assets table in the inventory_be_ct is the one with the autonumber unique field.

I tested with the code that you posted (ADO) and it works fine (after adding the quotes)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top