1

Looking to have the default INSERT INTO message where the count of records inserted is printed out. Know this has something to do with changing RETURNS from void to something else and possibly adding an OUT argument?

CREATE OR REPLACE FUNCTION etl(from_table regclass, to_table regclass) RETURNS void AS
$$
  BEGIN

  EXECUTE 'INSERT INTO ' || to_table || ' ('
      'title'
    ') '
    'SELECT '
      'data->>''title'' as title'
    'FROM ' || from_table || ' '
    USING from_table, to_table;

END
$$ LANGUAGE plpgsql;
4
  • 1
    Print out the SQL before executing it. The error will be obvious. Hint: think comma. Commented Mar 6, 2017 at 13:25
  • returning will return the actual values, not the count of rows affected Commented Mar 6, 2017 at 13:27
  • @GordonLinoff Thanks, deleted a bunch of select statements to simplify the example and created a buggy statement, fixed now. Good eyes! Commented Mar 6, 2017 at 13:28
  • The USING clause is superfluous and should be remove. Commented Mar 6, 2017 at 13:34

1 Answer 1

2

Use the GET DIAGNOSTICS command to populate, then return a variable:

CREATE OR REPLACE FUNCTION etl(from_table regclass, to_table regclass) RETURNS integer AS
$$
DECLARE
    rows integer;
BEGIN
    EXECUTE format('INSERT INTO %I (title) 
                        SELECT data->>''title'' as title
                        FROM %I', to_table, from_table);
    GET DIAGNOSTICS rows = ROW_COUNT;
    RETURN rows;
END;
$$ LANGUAGE plpgsql;

You should also really use the format() function to assemble your dynamic SQL command. Also, you can write literal strings over multiple lines without having to use ending/opening quotes at every line.

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.