7

How can I use my first with statement multiple times? With a code like below I can't use it for any other statement than the one that comes right after it.

WITH insertuser AS (

    INSERT INTO 
    zorro.user (username, firstname, lastname,
        accountstatus, roles, creationdatetime)
    VALUES('test', 'test', 'test',
        'test', 'test', current_timestamp)
    RETURNING id
    )

INSERT INTO
zorro.email (address, confirmed, count, user_id)
SELECT 'test', false, 1, id
FROM insertuser;

INSERT INTO
zorro.password (hash, count, user_id)
SELECT 'test', 1, id
FROM insertuser;

INSERT INTO
zorro.phone_number (number, confirmed, count, user_id)
SELECT 'test', false, 1, id
FROM insertuser;

INSERT INTO
zorro.Question (text, answer, count, user_id)
SELECT 'test', 'test', 1, id
FROM insertuser;

I get sql error at line 19, near the second "FROM insertuser" in the code.

3
  • whats the error throwing? Commented May 27, 2015 at 16:01
  • 2
    A common table expression is only valid for one query. Commented May 27, 2015 at 16:02
  • 1
    You can save the result to a temporary table and re-use the temporary table. Commented May 27, 2015 at 16:06

1 Answer 1

3

I think you can use a series of common table expressions:

WITH insertuser AS (
    INSERT INTO zorro.user (username, firstname, lastname, accountstatus, roles, creationdatetime)
        VALUES('test', 'test', 'test', 'test', 'test', current_timestamp)
     RETURNING id
    ),
    em as (
     INSERT INTO zorro.email (address, confirmed, count, user_id)
         SELECT 'test', false, 1, id
         FROM insertuser
     RETURNING *
    ),
    p as (
     INSERT INTO zorro.password (hash, count, user_id)
         SELECT 'test', 1, id
         FROM insertuser
     RETURNING *
    ),
    pn as (
     INSERT INTO zorro.phone_number (number, confirmed, count, user_id)
         SELECT 'test', false, 1, id
         FROM insertuser
     RETURNING *
   )
INSERT INTO zorro.Question (text, answer, count, user_id)
    SELECT 'test', 'test', 1, id
    FROM insertuser;

I am not 100% sure if the RETURNING clause is needed for the CTEs.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. btw the next RETURNING clauses are not needed.
@user3550283 were you able you get this thing working? I'm still facing issue.
@GauriShankarBadola . . . You should perhaps ask your own question.
@GordonLinoff Actually I was and then SO suggested me this. I have the very same issue and this thing doesn't work for me. :(

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.