IF ELSE 在 postgresql 函数中
IF ELSE in postgresql function
我正在尝试创建一个如下所示的函数
create function public.getSomething(
value1 integer
)
returns table (
id integer,
name varchar(20)
) as
$$
BEGIN
IF value1 = 0 THEN
select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
IF value1 = 1 THEN
select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
END;
$$ language SQL;
但是当我尝试创建时,出现以下错误
ERROR: syntax error at or near "if"
我尝试将语言从 SQL 更改为 plpgsql。但是这次我得到
Error: query has no destination for result data
Hint: if you want to discard the results of a select use perform instead
然后我用 Perform
替换了 Select
。这次创建了函数但是当我调用它时
没有结果!!
我做错了什么?还有其他选择吗?我正在使用 postgres 版本 12.3
稍作修改后的函数(大写):
- 语言是 plpgsql;
- 在 SQL 函数中,您只需 return 查询的结果。在 plpgsql 函数中,你必须使用
RETURN
语句来 return 任何东西。由于您不想丢弃查询结果而是 return 它们,因此在 SELECT 语句之前添加 RETURN QUERY
。
create OR REPLACE function public.getSomething(value1 integer)
returns table (id integer, name varchar(20)) as
$$
BEGIN
IF value1 = 0 THEN
RETURN QUERY select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
IF value1 = 1 THEN
RETURN QUERY select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
END;
$$ language PLPGSQL;
我正在尝试创建一个如下所示的函数
create function public.getSomething(
value1 integer
)
returns table (
id integer,
name varchar(20)
) as
$$
BEGIN
IF value1 = 0 THEN
select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
IF value1 = 1 THEN
select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
END;
$$ language SQL;
但是当我尝试创建时,出现以下错误
ERROR: syntax error at or near "if"
我尝试将语言从 SQL 更改为 plpgsql。但是这次我得到
Error: query has no destination for result data
Hint: if you want to discard the results of a select use perform instead
然后我用 Perform
替换了 Select
。这次创建了函数但是当我调用它时
没有结果!!
我做错了什么?还有其他选择吗?我正在使用 postgres 版本 12.3
稍作修改后的函数(大写):
- 语言是 plpgsql;
- 在 SQL 函数中,您只需 return 查询的结果。在 plpgsql 函数中,你必须使用
RETURN
语句来 return 任何东西。由于您不想丢弃查询结果而是 return 它们,因此在 SELECT 语句之前添加RETURN QUERY
。
create OR REPLACE function public.getSomething(value1 integer)
returns table (id integer, name varchar(20)) as
$$
BEGIN
IF value1 = 0 THEN
RETURN QUERY select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
IF value1 = 1 THEN
RETURN QUERY select a.id, b.name from table1 a inner join table2 b on a.Something = b.Something where
a.column = something and b.column = something;
END IF;
END;
$$ language PLPGSQL;