Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a stored procedure exists on PostgreSQL?

I'm pretty new to PostgreSQL and trying to learn PostgreSQL with the knowledge that I have on MS SQL Server & Oracle. I am looking for an equivalent of the following statement that we can use in MS SQL Server to check whether a Stored procedure exists or not, in PostgreSQL where SPName is your stored procedure's name.

SELECT 1 FROM sys.procedures WHERE Name = 'SPName')
SELECT 1 FROM sys.procedures WHERE object_id = OBJECT_ID(N'dbo.SPName')
like image 895
N00b Pr0grammer Avatar asked Dec 04 '25 17:12

N00b Pr0grammer


2 Answers

SELECT EXISTS (
        SELECT *
        FROM pg_catalog.pg_proc
        JOIN pg_namespace ON pg_catalog.pg_proc.pronamespace = pg_namespace.oid
        WHERE proname = 'proc_name'
            AND pg_namespace.nspname = 'schema_name'
        )

If you've not created a specific schema then use public(pg_namespace.nspname = 'public')


OR

You can create a custom function to do the task like below:

create or replace function function_exists (sch text,fun text) returns boolean as
$$
begin
EXECUTE  'select pg_get_functiondef('''||sch||'.'||fun||'''::regprocedure)';
return true;
exception when others then 
return false;
end;
$$ language plpgsql

and use :

select function_exists('public','function_name()')
like image 172
Vivek S. Avatar answered Dec 06 '25 10:12

Vivek S.


One-liner:

SELECT to_regproc('schema_name.proc_name') IS NOT NULL
like image 40
dedek Avatar answered Dec 06 '25 08:12

dedek