0

I have two tables where relationship one to many, and I want INSERT to mytable some values and RETURNING multiple values INTO variables to use them later. Here example:

 IF NOT EXISTS
        (SELECT id FROM mytable WHERE label_id = xxx)
    THEN
        INSERT INTO mytable
        (label_id, "name")
        VALUES
        (xxx,'foo'),
        (xxx,'bar')
    RETURNING 
        (SELECT id INTO mytable_id1 FROM mytable WHERE name = 'foo'),
        (SELECT id INTO mytable_id2 FROM mytable WHERE name = 'bar');
    ELSE 
        (SELECT id INTO mytable_id1 FROM mytable WHERE name = 'foo'),
        (SELECT id INTO mytable_id2 FROM mytable WHERE name = 'bar');
 END IF;

But I get always error:

ERROR: INTO specified more than once at or near "into"

I trying google problem and for example INSERT INTO ... RETURNING multiple columns (PostgreSQL) and Error: INTO specified more than once at or near "INTO"

unfortunately solutions it doesn't help for me (or I do something wrong). Any ideas?

0

1 Answer 1

0

I went the other way and a separate IF for each variable. Not very smart but its work

 IF NOT EXISTS
        (SELECT id FROM mytable WHERE label_id = xxx and "name"='foo')
    THEN
        INSERT INTO mytable
        (label_id, "name")
        VALUES
        (xxx,'foo'),
    RETURNING 
        (SELECT id INTO mytable_id1 FROM mytable WHERE name = 'foo');
    ELSE 
        (SELECT id INTO mytable_id1 FROM mytable WHERE name = 'foo');
 END IF;
 IF NOT EXISTS
        (SELECT id FROM mytable WHERE label_id = xxx and "name"='bar')
    THEN
        INSERT INTO mytable
        (label_id, "name")
        VALUES
        (xxx,'bar'),
    RETURNING 
        (SELECT id INTO mytable_id1 FROM mytable WHERE name = 'bar');
    ELSE 
        (SELECT id INTO mytable_id1 FROM mytable WHERE name = 'bar');
 END IF;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.