0

I am trying to write an sql function on PostgreSQL, but I have an error with the 'IF':

ERROR: Syntax error at or near "IF"
LINE 11: IF Type = 's' THEN

I can't understand the syntax error.
(The Function without the IF work correctly)

My SQL Code:

CREATE OR REPLACE FUNCTION public.add_activity(IDactivity smallint,Date_Start date, Data_End date, 
Type character varying,Name character varying DEFAULT NULL::character varying,
Typology character varying DEFAULT NULL::character varying, Client smallint DEFAULT NULL::smallint)
RETURNS void
LANGUAGE 'sql'
AS $BODY$

INSERT INTO public."Activity" 
VALUES(IDactivity, Date_Start, Data_End, Type, Name);

IF Type = 's' THEN
INSERT INTO public."Service" 
VALUES(IDactivity, Typology, Client); 

END IF;
$BODY$;

Thank you!

2
  • 2
    You cannot use if when you set the function language to SQL. You enable it using LANGUAGE plpgsql Commented Jan 7, 2022 at 16:29
  • @coladict thank you :) Commented Jan 7, 2022 at 17:01

1 Answer 1

2

IF is not implemented in the sql language but it is in the plpgsql language, see the manual.

You can either replace LANGUAGE sql by LANGUAGE plpgsql and then add BEGIN and END in the function body :

CREATE OR REPLACE FUNCTION public.add_activity(IDactivity smallint,Date_Start date, Data_End date, 
Type character varying,Name character varying DEFAULT NULL::character varying,
Typology character varying DEFAULT NULL::character varying, Client smallint DEFAULT NULL::smallint)
RETURNS void
LANGUAGE plpgsql
AS $BODY$
BEGIN
INSERT INTO public."Activity" 
VALUES(IDactivity, Date_Start, Data_End, Type, Name);

IF Type = 's' THEN
INSERT INTO public."Service" 
VALUES(IDactivity, Typology, Client); 
END IF;

END ;
$BODY$

Or you can change your code to stay in the sql language :

CREATE OR REPLACE FUNCTION public.add_activity(IDactivity smallint,Date_Start date, Data_End date, 
Type character varying,Name character varying DEFAULT NULL::character varying,
Typology character varying DEFAULT NULL::character varying, Client smallint DEFAULT NULL::smallint)
RETURNS void
LANGUAGE sql
AS $BODY$

INSERT INTO public."Activity" 
VALUES(IDactivity, Date_Start, Data_End, Type, Name);

INSERT INTO public."Service"
SELECT IDactivity, Typology, Client
WHERE Type = 's' ;

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

1 Comment

I used the second version, it was much simpler than I thought. I feel stupid, but after 10 hours on the screen my brain disconnected :D

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.