how to loop through table1 to select from table2, insert into table3

Posted on 2004-08-29
Last Modified: 2012-05-05
I have three tables in Access.
One is the original data (tblOriginal), containing 4 fields: StID,
Name, Pre, Type. One contains multiple records of selection criteria
(tblCriteria), three of which are used to match those in tblOriginal:
Name, Pre, and Type. The third table is the destination table
(tblAltNames), into which I want to insert matching records with all
four fields from tblOriginal.

I would like to loop through tblCriteria, building an SQL query for
each record that SELECTs FROM TblOriginal and INSERTs INTO

FYI - I'm using DAO so far because I figured it would be an easier
learning curve but it doesn't seem to be helping... Ultimately it
should be ADO anyway, so I'd appreciate advice for either. **Bonus
points** for ADO sol'n.

Here's what I have:

Public Sub BuildAltNamesTable()

Dim db As Database
Dim rec As Recordset
Dim strSELECT As String
Dim strFROM As String
Dim strINTO As String
Dim strWHERE As String
Dim strSQL As String

strSELECT = "StID, Name, Pre, Type"
strFROM = "tblOriginal"
strINTO = "tblAltNames"

Set db = CurrentDb()
Set rec = db.OpenRecordset(tblCriteria, dbOpenSnapshot)

Do While Not rec.EOF

 If IsNull(tblCriteria.Name) Then
   strWHERE = strWHERE & " AND tblCriteria.Name = tblOriginal.Name"
 End If

 If IsNull(tblCriteria.Pre) Then
   strWHERE = strWHERE & " AND tblCriteria.Pre = tblOriginal.Pre"
 End If

 If IsNull(tblCriteria.Type) Then
   strWHERE = strWHERE & " AND tblCriteria.Type = tblOriginal.Type"
 End If

 strSQL = "SELECT " & strSELECT
 strSQL = strSQL & "FROM " & strFROM
 strSQL = strSQL & "INTO " & strINTO
 If strWHERE <> "" Then
   strSQL = strSQL & "WHERE " & Mid$(strWHERE, 6)
 End If

[execute strSQL? help needed]


Set rec = Nothing

End Sub
Question by:molvo
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
  • 2
LVL 41

Expert Comment

ID: 11927861
To execute your SQL, just do:

CurrentDb.Execute strSQL

No real need to use ADO unless your back-end is something other than Jet.

Expert Comment

ID: 11927864
>> [execute strSQL? help needed]  <<

docmd.runSQL strSQL

LVL 41

Assisted Solution

shanesuebsahakarn earned 200 total points
ID: 11927873
A couple of points in favour of the Execute method over RunSQL - it doesn't pop up the confirmation dialogs, and can be around 25% faster. Both will work though.
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now


Author Comment

ID: 11928634
Thanks. The execute syntax was the hole I knew I was missing, but I was hoping for some help getting the rest to run as well. Mind if I ask for a bit more? After filling in the execute SQL line, I get a variable not defined error on tblCriteria in the If IsNull statements, e.g.,

If IsNull(tblCriteria.Name) Then   '****this is the line where the error occurs
   strWHERE = strWHERE & " AND tblCriteria.Name = tblOriginal.Name"
 End If

Any ideas?
And does the rest of the logic, structure, etc. look right?

BTW, eventually it will be shared by people with SQL Server DBs, so that's why I was thinking ADO, but I'm okay taking it slowly in DAO for now.

Thanks again.

Assisted Solution

rockmuncher earned 50 total points
ID: 11928646
You haven't set tblCriteria to be anything.  You should be using the rec recordset variable instead, like this

If IsNull(Rec!Name) Then
   strWHERE = strWHERE & " AND tblCriteria.Name = tblOriginal.Name"
 End If
LVL 41

Expert Comment

ID: 11928655
Hmm, without knowing what data your criteria table should hold, I couldn't say if the logic is right or not. However, some corrections you need to make to the code:

Set rec = db.OpenRecordset(tblCriteria, dbOpenSnapshot)
should read:
Set rec = db.OpenRecordset("tblCriteria", dbOpenSnapshot)

This opens a recordset based on the table called tblCriteria. The name has to be passed to OpenRecordset as a string, or a string literal (as I have done here). Now, whereever you have:
replace with:

So in your line:
If IsNull(tblCriteria.Name) Then
this will now read:
If IsNull(rec!Name) Then

Basically, now that you have opened a recordset called rec that is based on the table tblCriteria, rec contains all of the fields (and data) from tblCriteria. So you reference the recordset, not the table. Also note that you should never use "Name" as the name of a field - this can confuse Access, since "Name" is a reserved word. If you do use it, always enclose it between [] in code. So the above line should really read:
If IsNull(rec![Name]) Then
LVL 41

Expert Comment

ID: 11928666
Also, I suspect lines like this:
strWHERE = strWHERE & " AND tblCriteria.Name = tblOriginal.Name"

should read:
strWHERE = strWHERE & " AND tblOriginal.Name=" & rec![Name]

since you are trying to select from tblOriginal where the fields are equal to whatever data you have stored in tblCriteria (which you have just picked out in your recordset).
LVL 41

Accepted Solution

shanesuebsahakarn earned 200 total points
ID: 11928668
Sorry, if those are text fields, they should read:
strWHERE = strWHERE & " AND tblOriginal.Name=""" & rec![Name] & """"

Author Comment

ID: 11932521
Ah, much better. Thanks. I also realized that my If IsNull...Then statements were backward; I needed an If Not IsNull for that to execute correctly.

A belated clarification, everything is text fields except the ID field in tblOriginal.

Thanks for the reminder about Name being a reserved word -- no problems in my actual table because the real fieldname is longer. I simplified the field names for use here.

So now I'm focusing on the SQL statement itself. It still seems wrong. I'm thinking I need to build something like:
INSERT INTO tblAltNames SELECT StID, Name, Pre, Type FROM tblOriginal WHERE tblOriginal.Name = ...

I'll post this as a separate question here for more points. Thanks for all your help.

Featured Post

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Undo Button 1 35
Copy all value in one form to another 4 42
Error 438 6 19
docmd has stopped working 3 13
Introduction The Visual Basic for Applications (VBA) language is at the heart of every application that you write. It is your key to taking Access beyond the world of wizards into a world where anything is possible. This article introduces you to…
In Part II of this series, I will discuss how to identify all open instances of Excel and enumerate the workbooks, spreadsheets, and named ranges within each of those instances.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…

697 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