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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With