Solved

INSERT INTO + Update additional fields in the to file.

Posted on 2012-04-04
11
314 Views
Last Modified: 2012-04-06
I'm inserting data from one database to another but I also want it to update/populate additional fields that aren't in the original database.  How would I add that to the following code?

CurrentProject.Connection.Execute "INSERT INTO SupplierRFQSLT SELECT * FROM SUPPLIERRFQ"
0
Comment
Question by:CompTech810
11 Comments
 
LVL 10

Expert Comment

by:Michael Vasilevsky
Comment Utility
If the columns aren't in the target database you'll need to add them first with an ALTER statement. It has the following syntax:


ALTER TABLE table_name
  ADD column_name column-definition;
0
 
LVL 3

Expert Comment

by:Emenizer
Comment Utility
If you want to update some fields (or populate in case of empty) than you run an UPDATE query.
The syntax is something like this:
UPDATE table_name
SET column1=value, column2=value2
WHERE column0=value0

The values in the SET statement can also be references to or formulas using other columns instead of just hard-coded values.
0
 
LVL 49

Expert Comment

by:Gustav Brock
Comment Utility
You supply those values as expressions.
Rearrange your query like this:
INSERT INTO 
  SupplierRFQSLT 
  (FieldA, FieldB, FieldC, FieldD, FieldE)
SELECT 
  SourceFieldForFieldA,
  SourceFieldForFieldB,
  'SomeStringExpression' AS FieldC,
  1234 As FieldD,
  SourceFieldForFieldE
FROM 
  SUPPLIERRFQ

Open in new window


/gustav
0
 
LVL 2

Author Comment

by:CompTech810
Comment Utility
Maybe I'm thinking this the wrong way.

What I want to do I is loop through a query and create a new record(for each loop from query) in the SupplierRfqSlt file by writing all fields from the SupplierRFQ file, which is only one record, and while writing all the fields from SupplierRFQ populate a few fields that are in the SupplierRFQSlt file but not in the SupplierRFQ at the same time.  I want to be able to use '*' instead of typing each field and only type the few fields that do not come from SupplierRFQ.  I already have the loop working.
0
 
LVL 49

Expert Comment

by:Gustav Brock
Comment Utility
Here is how to do a fast copy of records using DAO avoiding a loop with SQL insert:
Public Sub CopyRecords()
  
  Dim rstSource   As DAO.Recordset
  Dim rstInsert   As DAO.Recordset
  Dim fld         As DAO.Field
  Dim strSQL      As String
  Dim lngLoop     As Long
  Dim lngCount    As Long

  strSQL = "SELECT * FROM tblStatus WHERE Location = '" & _
                "DEFx" & "' Order by Total"

  Set rstInsert = CurrentDb.OpenRecordset(strSQL)
  Set rstSource = rstInsert.Clone
  With rstSource
    lngCount = .RecordCount
    For lngLoop = 1 To lngCount
      With rstInsert
        .AddNew
          For Each fld In rstSource.Fields
            With fld
              If .Attributes And dbAutoIncrField Then
                ' Skip Autonumber or GUID field.
              ElseIf .Name = "Total" Then
                ' Insert default job code.
                  datNow = Now
                rstInsert.Fields(.Name).Value = 0
              ElseIf .Name = "PROCESSED_IND" Then
                rstInsert.Fields(.Name).Value = vbNullString
              Else
                ' Copy field content.
                rstInsert.Fields(.Name).Value = .Value
              End If
            End With
          Next
        .Update
      End With
      .MoveNext
    Next
    rstInsert.Close
    .Close
  End With
  
  Set rstInsert = Nothing
  Set rstSource = Nothing
  
End Sub

Open in new window

Of course, you will have to modify this to match the fields of your source query/table and to the field names of this.

/gustav
0
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
LVL 2

Author Comment

by:CompTech810
Comment Utility
I'm not a VBA programmer so I'm trying to understand the code you provided.

Is tblstatus the tabel that is being cloned to?  Please give a little explaination of what the code is doing, I'm kind of lost when I read the code.....  I'm a RPG programmer...
0
 
LVL 49

Expert Comment

by:Gustav Brock
Comment Utility
rstSource and rstInsert are the two recordsets. You will have to adjust the SQL for both as the code here is for copying records from a table to the same table.

It loops through the records, and for each record it loops through the fields, copying/inserting the value. The If .. Else If .. section is for exceptions to the straight copy done after the Else line.

/gustav
0
 
LVL 2

Author Comment

by:CompTech810
Comment Utility
Ok, I am pretty lost here......  I'm going to bump up the points because this is clear as mud.

Could you change your code to reflect the tables and two fields that don't exist in the to table.

The table that I'm reading from is SupplierRFQ, it has one record.  I want to copy that one record to SupplierRFQSlt which is identical to the SupplierRFQ with the exception of a few fields.  I am using a query that loops through a contact database that has contacts.  I need to add the record from SupplierRFQ to SupplierRFQSlt for each contact in the query and populate the additional fields in SupplierRFQSlt during that add.

The query loop I have in place is working fine with the exception of adding the single record to the table SUpplierRFQSlt for each contact the query finds..
0
 
LVL 49

Accepted Solution

by:
Gustav Brock earned 250 total points
Comment Utility
That would be something like this (air code):
Public Sub CopyRecords()
  
  Dim rstSource   As DAO.Recordset
  Dim rstInsert   As DAO.Recordset
  Dim fld         As DAO.Field
  Dim strSQL      As String
  Dim lngLoop     As Long
  Dim lngCount    As Long

  strSQL = "SELECT * FROM SupplierRFQ"
  Set rstSource = CurrentDb.OpenRecordset(strSQL)

  strSQL = "SELECT * FROM SupplierRFQSlt"
  Set rstInsert = CurrentDb.OpenRecordset(strSQL)

  With rstSource
    lngCount = .RecordCount
    For lngLoop = 1 To lngCount
      With rstInsert
        .AddNew
          ' Copy fields from source table.
          For Each fld In rstSource.Fields
            With fld
              If .Attributes And dbAutoIncrField Then
                ' Skip Autonumber or GUID field.
              Else
                ' Copy field content.
                rstInsert.Fields(.Name).Value = .Value
              End If
            End With
          Next
          ' Insert fixed values. Adjust to your needs:
          rstInsert.Fields("YourFirstAdditionalFieldName").Value = dblSomeValue
          rstInsert.Fields("YourSecondAdditionalFieldName").Value = strSomeString
          ' etc.
          rstInsert.Fields("YourLastAdditionalFieldName").Value = lngSomeOtherValue
        .Update
      End With
      .MoveNext
    Next
    rstInsert.Close
    .Close
  End With
  
  Set rstInsert = Nothing
  Set rstSource = Nothing
  
End Sub

Open in new window


dblSomeValue etc. must either be passed as parameters or declared (Dim'ed) in the function and assigned proper values matching the data types of the fields of table SupplierRFQSlt.
/gustav
0
 
LVL 2

Author Closing Comment

by:CompTech810
Comment Utility
I actually used an apend query, check this link.  I still want you to have the points for all your help!

http://www.experts-exchange.com/Microsoft/Development/Q_27665148.html
0
 
LVL 49

Expert Comment

by:Gustav Brock
Comment Utility
That could be used as well for one record. If many records, the VBA method is way faster.

/gustav
0

Featured Post

Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

Join & Write a Comment

Suggested Solutions

In the previous article, Using a Critera Form to Filter Records (http://www.experts-exchange.com/A_6069.html), the form was basically a data container storing user input, which queries and other database objects could read. The form had to remain op…
I originally created this report in Crystal Reports 2008 where there is an option to underlay sections. I initially came across the problem in Access Reports where I was unable to run my border lines down through the entire page as I was using the P…
In Microsoft Access, learn different ways of passing a string value within a string argument. Also learn what a “Type Mis-match” error is about.
In Microsoft Access, when working with VBA, learn some techniques for writing readable and easily maintained code.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now