Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a boolean value returned from a function to a variable in PostgreSQL 9.4?

I have a function that checks whether a table exists on PostgreSQL or not, using the following code:

CREATE OR REPLACE FUNCTION public.sp_table_exists(p_in_table_name character varying)
  RETURNS boolean AS
$$
    DECLARE QUERY_COUNT INTEGER DEFAULT 1;
    QUERY_STRING VARCHAR(300);
    BEGIN
        QUERY_STRING := CONCAT('SELECT RELNAME FROM PG_CLASS WHERE RELNAME = ''',p_in_table_name,'''');
        EXECUTE QUERY_STRING;
        GET DIAGNOSTICS QUERY_COUNT = ROW_COUNT;
        IF QUERY_COUNT > 0  THEN
            RETURN TRUE;
        ELSE
            RETURN FALSE;
        END IF;     
    END;
$$ LANGUAGE plpgsql;

I'm trying to use the output of the above function to assign to a boolean value, but PostgreSQL doesn't allow me to do so.

DECLARE DEBUG_ENABLED boolean DEFAULT FALSE;
DEBUG_ENABLED := PERFORM sp_table_exists('temp_table');

OR

DEBUG_ENABLED := SELECT * FROM sp_table_exists('temp_table');

Can you please help me resolve this?

like image 782
N00b Pr0grammer Avatar asked Sep 16 '25 12:09

N00b Pr0grammer


1 Answers

Perform, to the best of my understanding, lets you execute a function without returning any value(s). As such, it makes sense that this would return nothing.

As far as assigning it to your variable, I think it's easier than you imagined:

DEBUG_ENABLED := sp_table_exists('temp_table');

select ... into is generally used when you have a field or value from a query that you want in a variable (which isn't your situation):

select count (*) > 0
into DEBUG_ENABLED
from information_schema.tables
where table_name = 'temp_table'
like image 57
Hambone Avatar answered Sep 18 '25 09:09

Hambone