Home > database >  Select no-rows or string with a function
Select no-rows or string with a function

Time:06-13

I am using Postgre.

I have a function that checks for existence of a table, and then checks for specific field in row data field which is jsonb, and returns row id. I am trying to make it so in case of failure it returns no rows.

It does that in case table exists but condition is not met to find a row i.e. the EXECUTE line. How can I return no rows instead of an empty string (best thing I could come up with atm) in ELSE clause, which happens when table doesn't exist?

CREATE OR REPLACE FUNCTION id_by_data_field
(
    _field text,
    _value text,
    _table text
)
RETURNS TABLE (_id text)
AS
$$
BEGIN
  IF EXISTS(SELECT *
        FROM pg_tables
        WHERE schemaname = 'public'
        AND tablename = _table) THEN
    RETURN QUERY 
        EXECUTE 'SELECT CAST(id AS text) FROM '|| _table ||' WHERE data->>'''|| _field ||''' = '''|| _value ||'''';
  ELSE
    RETURN QUERY SELECT '';
  END IF;
END;
$$
LANGUAGE plpgsql;

CodePudding user response:

Simply remove the following from your function:

  ELSE
    RETURN QUERY SELECT '';
  • Related