views:

32

answers:

2

Hi,

I'm an SQL newbie and trying to figure out how to insert multiple table entries in one SQL statement. Here is my code:

INSERT INTO [Students](P_Id,FirstName,LastName,class,city,Phone)
SELECT 123,'Avi','Davis',2,'Tel-Mond','03-456789'
UNION
SELECT 234, 'Dani',2,'Dimona',' 02-111'
UNION 
SELECT 345,'Itzik',3,'Ariel', '03-2222'
UNION 
SELECT456, 'Koby', 3, 'Tel-Aviv', '03-333333'
UNION 
SELECT 789,'Moshe' ,2 , 'Tel-Aviv','03-7777777'

I've tried all sorts of variations on the theme with "help" from various tutorials, but nothing I've tried works so far. It seems like with each different DB program SQL usage differs slightly.

Any suggestions as to how to change my code so that it will work with MS Access?

+1  A: 

You can do something like that in MS Access, but you must have a from table, and you must take care that only one row is returned:

INSERT INTO [Students](P_Id,FirstName, LastName, class,  city,Phone)
SELECT 123 As P_ID, 'Avi' As FirstName, 'Davis' As LastName, 2 As Class,
        'Tel-Mond' As City,'03-456789' As Phone FROM AnyTable
UNION
<...>

It can be easier to use VBA and loop.

Remou
You can ensure only one row is returned by including "top 1" in the select statements. See http://stackoverflow.com/questions/62504/ for an example. You may want to create a dummy/utility table to do tricks like this (like Oracle's DUAL table), rather than mixing it up with a table that contains "real" data.
CodeSlave
UNION will do it, too. UNION is unique values, UNION ALL is more than one of a kind.
Remou
A: 

Access will only run one SQL statement in a query. Normally in Access you would load data from a csv file or spreadsheet. If you really want to do it in SQL get a client like iSQLviewer which will connect to most databases (I haven't tried it with Access) and will run scripts.

MikeAinOz
While it's true that Jet/ACE is restricted to one SQL statement at a time, the original question lists only one SQL statement (INSERT INTO...SELECT UNION...), so I'm not sure what your point is.
David-W-Fenton
Pardon me for not being clearer. Typically multi-row inserts are generated by multiple insert statements in a script. Access has a real weakness here in that it can't execute a multi-statement SQL script. Hence my comment that it is easier to use an SQL client to perform scripts rather than trying to work around it in Access.
MikeAinOz