Postgresql 返回前检查Postgres函数中的结果计数

Postgresql 返回前检查Postgres函数中的结果计数,postgresql,Postgresql,我有一个postgres函数,我想返回一个查询的结果,但是如果该查询匹配多个记录,我希望它什么也不返回 比如说: CREATE OR REPLACE FUNCTION myFunc(_a text, _b text) RETURNS yy LANGUAGE plpgsql STABLE PARALLEL SAFE AS $$ BEGIN RETURN QUERY SELECT * FROM yy WHERE a = x AND b =

我有一个postgres函数,我想返回一个查询的结果,但是如果该查询匹配多个记录,我希望它什么也不返回

比如说:

CREATE OR REPLACE FUNCTION myFunc(_a text, _b text)
  RETURNS yy
  LANGUAGE plpgsql
  STABLE
  PARALLEL SAFE
  AS $$
BEGIN
  RETURN QUERY
    SELECT *
    FROM yy
    WHERE a = x
      AND b = y;
END;
$$;

但是,如果查询匹配的记录超过1条,则不应返回任何内容。

我想这可以帮助您解决问题

CREATE OR REPLACE FUNCTION database.myFunction(
IN text,IN text)

RETURNS TABLE(firstField, secondField, lastField) AS
$BODY$
--sql string is the variable containing the final sql code
declare sql_string text;
declare regs numeric;


begin
--this is what happens in case count<1
sql_string = 'select 0,0,0';

--now we count them
regs = (select count(firstField) from mytable where a=b)::numeric;

--if >=1, then whe get the whole data
if (regs>=1) then

    sql_string = 'select firstField,secondField, lastField from mytable where a=b';

end if;
--and return to you...
return query EXECUTE sql_string;
end;
创建或替换函数数据库.myFunction(
在文本中,在文本中)
将表(firstField、secondField、lastField)返回为
$BODY$
--sql字符串是包含最终sql代码的变量
声明sql_字符串文本;
声明regs数字;
开始
--这是当count=1时发生的情况,然后当我们得到整个数据时
如果(regs>=1),则
sql_字符串='从mytable中选择firstField、secondField、lastField,其中a=b';
如果结束;
--回到你身边。。。
返回查询执行sql\u字符串;
结束;
CREATE OR REPLACE FUNCTION myFunc(_a text, _b text)
  RETURNS SETOF yy -- To be able to return "nothing"
  LANGUAGE plpgsql
  STABLE
  PARALLEL SAFE
  AS $$
DECLARE
  result yy;
BEGIN
  SELECT *
  INTO STRICT result -- STRICT allows to check that exactly one row returned
  FROM yy
  WHERE a = x
    AND b = y;
  RETURN NEXT result; -- RETURN NEXT - return yet another row for "RETURNS SETOF" function
EXCEPTION
  WHEN no_data_found OR too_many_rows THEN -- When no data or more then one rows
    RETURN; -- Nothing to return, just exit
END;
$$;