PostgreSQL 中 "IF" 处或附近的语法错误

Syntax error at or near "IF" in PostgreSQL

我正在尝试在 PostgreSQL 上编写一个 sql 函数,但是 'IF':

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

我无法理解语法错误。
(没有 IF 的函数可以正常工作)

我的SQL代码:

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$;

谢谢!

IF 未在 sql 语言中实现,但在 plpgsql 语言中实现,请参阅 manual.

您可以将 LANGUAGE sql 替换为 LANGUAGE plpgsql,然后在函数体中添加 BEGINEND

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$

或者您可以更改代码以保留 sql 语言:

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$