Select From One Table, Insert Into Two Other Tables Based On Condition
I have a Postgres database with 3 tables, say A, B and C. I want to select data from table A and loop through each row checking the value in one of the columns and then insert the
Solution 1:
You don't need a cursor for this, you don't need plpgsql, you don't even need a data-modifying CTE which would allow you to do that in a single SQL statement.
Just run two plain INSERT statements. Put them in a transaction if you want to make sure all or nothing is applied:
BEGIN;
INSERTINTO B (col1, col2)
SELECT col1, col2
FROM A
WHERE col_cond ='something';
INSERTINTO C (col1, col2)
SELECT col1, col2
FROM A
WHERE col_cond ISDISTINCTFROM'something';
COMMIT;
Solution 2:
User cursor for select statement on table A, see this link
Inside the cursor you can check condition and run insert statements on B or C
For code example see this link
Cheers !!
Solution 3:
Type the following commands:
begin;
insertinto table_name asselect*from table_name2 where Name="?";
commit;
Post a Comment for "Select From One Table, Insert Into Two Other Tables Based On Condition"