2

I am trying to create the following function in a postgres_9 database:

CREATE OR REPLACE FUNCTION getUser(IN user_id INT8)
RETURNS TABLE(id INT8, nom TEXT, prenom TEXT)
AS $$
    BEGIN
        SELECT id, nom, prenom 
        FROM security.users
        WHERE id = user_id
    END
$$ LANGUAGE sql;

But I get the following error:

ERROR: syntax error at or near "SELECT"

PS: I am new to Postgres databases. if you have good resources for tutorials and books on how to create functions and triggers in plpgsql or SQL for Postgres databases that would be great!

5
  • 2
    Remove BEGIN and END.
    – klin
    May 18, 2017 at 8:18
  • Thank you !! but now I have a new ERROR: ERROR: column "user_id" does not exist May 18, 2017 at 8:23
  • How do you call this function ? May 18, 2017 at 8:24
  • Why are you using an outdated and unsupported Postgres version? May 18, 2017 at 8:43
  • what version should I use? May 18, 2017 at 8:45

2 Answers 2

1

Can you try with this approach as suggested in this Postgresql 9.1 Create Function

CREATE FUNCTION getUser(int)
RETURNS TABLE(id int, nom text, prenom text)
AS $$ SELECT id, nom, prenom 
      FROM security.users
      WHERE id = $1 $$
LANGUAGE SQL;
1
  • now I get ERROR: syntax error at or near "SELECT" May 18, 2017 at 8:29
0

PostgreSQL has two default languages for stored procedures (function): PLpgSQL and SQL. SQL is raw SQL. PLpgSQL is ADA based procedural language with block structure - block is defined by keywords BEGIN, END. You can write your function in both these languages. You should to specify language correctly.

CREATE OR REPLACE FUNCTION getUser(IN user_id INT8)
RETURNS TABLE(id INT8, nom TEXT, prenom TEXT)
AS $$
BEGIN
  RETURN QUERY SELECT id, nom, prenom 
                 FROM security.users
                 WHERE id = user_id;
END
$$ LANGUAGE plpgsql;

or

CREATE OR REPLACE FUNCTION getUser(IN user_id INT8)
RETURNS TABLE(id INT8, nom TEXT, prenom TEXT)
AS $$
   SELECT id, nom, prenom 
     FROM security.users
    WHERE id = $1 
$$ LANGUAGE sql;

SQL language in 9.1 doesn't support named parameters, so you should to use $1, $2, ... for parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.