0

We assume that there exists a table terms(id,year,sess). sess is the semester S1 or S2.

create function Q3(id1 IN integer) returns TextString 
declare tm TextString
begin
      SELECT 'year%100'||lower(sess) into tm
      FROM Terms 
      WHERE id1 = id
      return tm
END;

I got an error near declare, what's wrong with my code?

3
  • How to write PL/pgSQL functions Commented Apr 20, 2014 at 18:38
  • Thank you for apply, I tried this but still got an error near declare,does my code have any other syntax error near declare? Commented Apr 20, 2014 at 18:40
  • I just want to modify the column id of terms into format like'12s1',what will you do targeting this purpose? Commented Apr 20, 2014 at 18:43

1 Answer 1

1

It is almost all wrong. PostgreSQL stored procedures are written as string - you miss it, and you miss a language specification. Probably you want:

CREATE OR REPLACE FUNCTION Q3(_id integer)
RETURNS text AS $$
DECLARE _tm text;
BEGIN
  SELECT t.year % 100 || lower(t.sess) INTO _tm
     FROM terms t
    WHERE _id = t.id;
  RETURN _tm;
END;
$$ LANGUAGE plpgsql;

This code can be truncated little bit or you can use SQL language for trivial one line functions:

CREATE OR REPLACE FUNCTION Q3(id integer)
RETURNS text AS $$
SELECT t.year % 100 || lower(t.sess)
   FROM terms t
  WHERE t.id = $1;
$$ LANGUAGE sql;

see http://postgres.cz/wiki/PL/pgSQL_%28en%29

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

3 Comments

that's exactly what I need, but I got another error: unterminated dollar-quoted string at or near "$$
Excuse me for abusing a comment, but I would like to draw your attention to this one: dba.stackexchange.com/questions/40214/…, for two reasons: Did I miss anything? What do you think about my feature wish?
I dislike it - It is implementable, and probably simply. But I am not sure, so a request for this feature is valid - it navigates a users to bad (too dynamic) design. Stored procedures should be simple and if is possible static. Then it is fast and readable. Stored procedures should not to supply client (visualization) job.

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.