0

I'm trying the update a table using the function below. The table name is a function argument. Running this function results in the error:

ERROR: syntax error at or near "$1" LINE 1: (SELECT * FROM $1 ORDER BY $2 )

I tried using the EXECUTE statement and the quote_ident function, but without success sofar. I'm sure I'm overlooking something simple...

CREATE OR REPLACE FUNCTION createdefaultorder(table_name varchar, sort_column varchar)
  RETURNS integer AS
$BODY$
DECLARE
  rRec RECORD;
  counter integer := 0;
BEGIN
  FOR rRec IN  (SELECT * FROM table_name ORDER BY sort_column)  LOOP
    UPDATE table_name SET row_number = counter WHERE id = rRec.id;
    counter := counter + 1;
  END LOOP; 
  RETURN 0;
END;
$BODY$
  LANGUAGE plpgsql;
1
  • Please either accept an answer or update your question. The code you provided does not appear relevant to the error you posted at the top. Commented Dec 9, 2015 at 22:47

3 Answers 3

5

Using EXECUTE and quote_ident is the correct solution. If you have trouble with that, you might want to show that code.

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

1 Comment

Thanks for pointing me in the right direction. I managed the get the required result with the following function: ` BEGIN FOR rRec IN EXECUTE 'SELECT * FROM ' || quote_ident(table_name) || ' ORDER BY ' || quote_ident(sort_column) LOOP EXECUTE 'UPDATE ' || quote_ident(table_name) || ' SET row_number = ' || counter || ' WHERE id = ' || rRec.id; counter := counter + 1; END LOOP; RETURN 0; END; `
0

Execute and quote_ident are the solution to that problem: PostgreSQL 8.4 Manual

Comments

0

You must use EXECUTE and quote_ident() in a dynamic query execution like this:

BEGIN FOR rRec IN EXECUTE 'SELECT * FROM ' || quote_ident(table_name) || ' ORDER BY ' || quote_ident(sort_column) LOOP EXECUTE 'UPDATE ' || quote_ident(table_name) || ' SET row_number = ' || counter || ' WHERE id = ' || rRec.id; counter := counter + 1; END LOOP; RETURN 0; END;

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.