Reputation: 279
is there a simple way to make insert to a table using values from another table?
Lets say I have to fetch the NAME value from T1 and I want to make a hardcoded insertion to another table using that value.
The insertion values should be something like
INSERT INTO T2 (NAME, AGE, GENDER) VALUES (NAME, 22, 'M')
Name is fetched from T1, 22 and 'M' are hardcoded in the insert query.
Upvotes: 1
Views: 72
Reputation: 46
You can do a select in an insert:
INSERT INTO T2 (NAME, AGE, GENDER)
SELECT NAME, 22, 'M' FROM T1
Also handy because you can ditch the insert and just run the select to test what you are importing before you do it, and easy to add a WHERE NOT EXISTS
to make it idempotent.
Upvotes: 3
Reputation: 312259
You can use an insert-select statement, where you select literals for the values you want:
INSERT INTO t2
SELECT name, 22, 'M'
FROM t1
Upvotes: 2
Reputation: 1271151
Yes . . . insert . . . select
:
insert into t2 (name, age, gender)
select name, 22, 'M'
from t1;
Upvotes: 3