我在postgresql中创建一个函数,它将执行以下操作:
CREATE OR REPLACE FUNCTION check_label_id_exist(_labelid integer, OUT result text) AS
$BODY$
DECLARE
BEGIN
SELECT pkid FROM table_1 WHERE label_id = _labelid;
IF FOUND THEN
result := 'true';
RETURN;
IF NOT FOUND THEN
SELECT pkid FROM table_2 WHERE label_id = _labelid;
IF FOUND THEN
result := 'true';
RETURN;
IF NOT FOUND THEN
SELECT pkid FROM table_3 WHERE label_id = _labelid;
IF FOUND THEN
result := 'true';
RETURN;
IF NOT FOUND THEN
result := 'false';
RETURN;
END
$BODY$ language plpgsql;
此处该函数首先在table_1
中查找数据。如果没有数据,那么它将转到下一个表,依此类推。如果任何表有数据,它将破坏条件并返回true,否则最终将返回false。我认为我在这里写的代码不正确。请帮助实现我的目标。
答案 0 :(得分:4)
这可能是一种更简单的方法,可以用较少的代码来完成您正在尝试的操作。
CREATE OR REPLACE FUNCTION check_label_id_exist(_labelid integer, OUT result text) as
$BODY$
BEGIN
IF EXISTS(SELECT 1 FROM table_1 WHERE label_id = _labelid limit 1) THEN
result := 'true';
ELSEIF EXISTS(SELECT 1 FROM table_2 WHERE label_id = _labelid limit 1) THEN
result := 'true';
ELSEIF EXISTS(SELECT 1 from table_3 WHERE label_id = _labelid limit 1) THEN
result := 'true';
ELSE
result := 'false';
END IF;
RETURN;
END
$BODY$ language plpgsql;
答案 1 :(得分:0)
CREATE OR REPLACE FUNCTION check_label_id_exist(_labelid integer,
OUT result text) AS
$BODY$
DECLARE
BEGIN
SELECT pkid FROM table_1 WHERE label_id = _labelid;
IF FOUND THEN
result := 'true';
RETURN;
end if;
SELECT pkid FROM table_2 WHERE label_id = _labelid;
IF FOUND THEN
result := 'true';
RETURN;
end if;
SELECT pkid FROM table_3 WHERE label_id = _labelid;
IF FOUND THEN
result := 'true';
RETURN;
end if;
result := 'false';
RETURN;
END
$BODY$ language plpgsql;