patternsqlMinor
Postgresql - Can I do a join in a function?
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;
If the user return the @opt variable with 1 the result could be like:
and if the user return a 2 in the @opt it would be something like:
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
GOIf 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 | qerand if the user return a 2 in the @opt it would be something like:
nothingSolution
Yes, except the Postgres syntax through
If you need a more complex procedural language check out
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/pgSQLCode 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.