ApplePie
ApplePie

Reputation: 8942

Insert multiple records in a single time using VBA Access

I am trying to avoid using multiple INSERT SQL queries but if I must I will. I have read over there that you can simply use INSERT INTO table(field) SELECT 'value' UNION ALL SELECT ... however I am having trouble with the syntax of it under MS Access 2007. I have tried a few variants but none works: I always get either "incorrect syntax" or "missing operator" error. I have tried with and without the ALL qualifier, with and without the SELECT keyword, etc. Here's how I am creating the query using VBA:

sql_query = "INSERT INTO " & tmp_tbl_name & " (transit)"
For Each xlCell In xlRange
    sql_query = sql_query & " SELECT '" & xlCell.Value & "' "
    sql_query = sql_query & "UNION"
Next xlCell
sql_query = Mid(sql_query, 1, Len(sql_query) - 6)
DoCmd.RunSQL (sql_query)

Here's a shortened sample of the query I am generating:

INSERT INTO tmp_tbl_2012_08_17_15_44_03 (transit) 
SELECT 'L02_NA010001' 
  UNION 
SELECT 'L13_PB010001' 
  UNION 
SELECT 'L31_US020001' 
  UNION 
SELECT 'L33_EX020010'
  ...

The table has only one VARCHAR(255) field and no relations to any other table (it's a temporary table to process a few things and keep only some elements of it).

Many thanks !

Upvotes: 2

Views: 9725

Answers (2)

Jim
Jim

Reputation: 3510

I think you can use good ol' DAO to do this rather quickly:

Dim db As DAO.Database
Dim rs As DAO.Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("tmp_tbl_2012_08_17_15_44_03", dbOpenDynaset)

For Each xlCell In xlRange
    With rs
        .AddNew
        .Fields("transit") = xlCell.Value
        .Update
    End With
Next xlCell

rs.Close
db.Close

Upvotes: 3

Fionnuala
Fionnuala

Reputation: 91306

It will probably be easier to run the statements one at a time in MS Access, the UNION will require FROM Table for each UNION statement, which means the FROM table will have to contain just one row, or a little fancy footwork.

INSERT INTO tmp_tbl_2012_08_17_15_44_03 (transit) 
SELECT Transit FROM (
SELECT DISTINCT 'L02_NA010001' As Transit FROM tablename
  UNION 
SELECT DISTINCT 'L13_PB010001' As Transit FROM tablename
  UNION  ... )

Upvotes: 1

Related Questions