Reputation: 1938
I'm trying to insert new rows into my DB. I have 155 rows that I need to insert. What is happening is that I am adding new users based on an existing account table. I have a query that lists the new users that I need to add to the users table, but I don't want to have to type out the insert 155 times. Is there an easier way of doing this? I've seen where you can have multiple sets of 'Values' in the insert, but I'm not sure how I would implement this. For example:
insert into tblUsers (State,City,Code)
Values ('IN','Indy',(select UserCode from tblAccounts where UserCode in(Select UserCode from tblAccounts where State = 'IN')))
I know that my sub-query will return 155 values and so won't actually work here, is there a way to modify this so that it will work?
Upvotes: 0
Views: 96
Reputation: 3289
Try this:
INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE UserCode IN
(SELECT UserCode
FROM tblAccounts
WHERE State = 'IN')
or better simplified (a subquery is not needed):
INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE State = 'IN'
Upvotes: 1
Reputation: 9724
Query:
INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE State = 'IN'
Upvotes: 1
Reputation: 480
You can only insert from another table, like this:
insert into tblUsers (State,City,Code)
SELECT * FROM table1
Upvotes: 0
Reputation: 3137
Try this...
INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE UserCode IN (SELECT UserCode FROM tblAccounts WHERE State = 'IN')
Upvotes: 1
Reputation: 8877
insert into tblUsers (State,City,Code)
Select 'IN','Indy', UserCode
from tblAccounts
where UserCode in (Select UserCode
from tblAccounts
where State = 'IN')
Upvotes: 1