I cannot do a function that returns a Semester of a Date in Postgresql

Asked

Viewed 470 times

1

I’m trying to make a conversion that returns a semester of a date, but this error has appeared here

CREATE or REPLACE FUNCTION semestre ( data timestamp )
RETURNS INTEGER AS
$$
BEGIN
    IF data <= 6
        THEN return 1;
    ELSE
        return 2;
    END IF;
RETURN -1;
END
$$
LANGUAGE 'plpgsql';

SELECT semestre(timestamp '16/06/2017');

Error message:

ERRO:operador não existe: timestamp without time zone <= integer
LINE 1: SELECT   $1  <= 6
                     ^
HINT:  Nenhum operador corresponde com o nome e o(s) tipo(s) de argumento(s) informados. Você precisa adicionar conversões de tipo explícitas.
QUERY:  SELECT   $1  <= 6
CONTEXT:  PL/pgSQL function "semestre" line 2 at IF

what could be?

1 answer

1


You are trying to compare a timestamp with a whole, you have to compare only the month.

do so:

 if date_part('month',data ) <=6

That would be the job:

CREATE or REPLACE FUNCTION semestre ( data timestamp )
RETURNS INTEGER AS
$$
BEGIN
    IF date_part('month',data ) <=6
        THEN return 1;
    ELSE
        return 2;
    END IF;
RETURN -1;
END
$$
LANGUAGE 'plpgsql';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.