简体   繁体   中英

How to insert multiple rows into an SQL table when the values for one (or more) of the columns need to be derived from another table?

I cannot for the life of me find an answer to this extremely simple question.

What is the correct way to insert multiple rows into an SQL table when the values for one (or more) of the columns need to be derived from another table?

This is what I'm trying to do, using SQL Anywhere:

INSERT INTO Table (ColName1, ColName2, ColName3FK) VALUES

('foo', 'bar', (SELECT OtherTable.ID FROM OtherTable WHERE SomeCol = 'something')),
('doo', 'dar', (SELECT OtherTable.ID FROM OtherTable WHERE SomeCol = 'something')),
('goo', 'gar', (SELECT OtherTable.ID FROM OtherTable WHERE SomeCol = 'something'));

This throws an error saying 'Invalid value for INSERT' at the second SELECT statement. Sure enough, if I attempt to insert a single line the same way, it works fine:

INSERT INTO Table (ColName1, ColName2, ColName3FK) VALUES

('foo', 'bar', (SELECT OtherTable.ID FROM OtherTable WHERE SomeCol = 'something'));

Also, manually looking up the IDs I need and typing them in works with multiple lines:

INSERT INTO Table (ColName1, ColName2, ColName3FK) VALUES

('foo', 'bar', 42),
('doo', 'dar', 42),
('goo', 'gar', 42);

I have tried assigning the IDs I need to variables and using them in the INSERT statement with no luck (although I haven't spent too much time trying to do that, so I might have used incorrect syntax or sth). I have tried doing a similar thing using the WITH statement as well.

what you can do it's try to get the id outside of the query and after insert the rows like this.

var id = SELECT OtherTable.ID FROM OtherTable WHERE SomeCol = 'something' ;

(look at the id result and get the id )

INSERT INTO Table (ColName1, ColName2, ColName3FK) VALUES
('foo', 'bar', id),
('doo', 'dar',,id ),
('goo', 'gar',id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM