HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Postgresql - Can I do a join in a function?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlcanfunctionjoin

Problem

I'm recently starting to use PostgreSQL. In SQL Server I used to use stored procedures for different kind of things. I want to know if, like in SQL Server, can I do something like in that.
I used to use this kind of things;

create procedure my_proc
@opt int=null,
@param varchar=null
AS BEGIN
IF @opt = 1 
 select * from my_table1 t1
 inner join table2 on t1.id=t2.id 
 where t2.param=@param
END IF
IF @opt = 2
select "nothing"
END IF

GO


If the user return the @opt variable with 1 the result could be like:

t1_id | t2_id | param
2     | 2     | qer
5     | 1     | qer
8     | 1     | qer


and if the user return a 2 in the @opt it would be something like:

nothing

Solution

Yes, except the Postgres syntax through CREATE FUNCTION is more natural:

CREATE FUNCTION my_proc(myOpt bool, myParam varchar)
RETURNS SETOF (types)
AS $
  SELECT types
  FROM my_table1 t1
  INNER JOIN table2 AS t2 USING (id)
  WHERE myOpt AND t2.param = myParam
$ LANGUAGE sql;


If you need a more complex procedural language check out PL/pgSQL

Code Snippets

CREATE FUNCTION my_proc(myOpt bool, myParam varchar)
RETURNS SETOF (types)
AS $$
  SELECT types
  FROM my_table1 t1
  INNER JOIN table2 AS t2 USING (id)
  WHERE myOpt AND t2.param = myParam
$$ LANGUAGE sql;

Context

StackExchange Database Administrators Q#194909, answer score: 3

Revisions (0)

No revisions yet.