tags:

views:

407

answers:

2

I need to make a select query with joins. This should be written in a function. My approach didn't work:

CREATE OR REPLACE FUNCTION test2()
RETURNS SETOF record AS'
DECLARE
    r record;
BEGIN
    for r in SELECT * FROM messages_wall INNER JOIN location ON
         messages_wall.id = location.id
         loop
    return next r;
    end loop;
end; '
LANGUAGE 'plpgsql'

ERROR: a column definition list is required for functions returning "record"

I should call this function from a .net application. How should I proceed?

+1  A: 

Instead joining table into your function, you may use view.

RETURNS SETOF your_view;

You probably have to define r with the appropriate datatype too:

r your_view%ROWTYPE;

or

You have to specify the fields and datatype.

SELECT * FROM test2() AS fields_1 as INTEGER, fields_2 AS ... ;
Luc M
Ok, how can I do this using Npgsql, in ado.net?
Markus
RETURNS SETOFF messages_wall - doesn't work
Markus
Sorry, RETURNS SETOF should work.
Luc M
You can't use SETOF messages_wall because that table is joined with the location table, resulting in a table with more columns than messages_wall. You'll need to define a new type that has the appropriate fields in it.
Barry Brown
It works indeed with r messages_wall%ROWTYPE. But what if I want to return the values from different tables:for r in SELECT messages_wall.id, location.name FROM messages_wall INNER JOIN location ON messages_wall.id = location.id
Markus
In this case that approach does not work.
Markus
@Barry, I didn't remark the JOIN... Only specifying fields and datatypes works.
Luc M
Ok, as I understand, if I specify fields and datatypes, I cannot use ExecuteReader() with command type stored procedure?
Markus
+1  A: 

For your example wrapping a join in a (PL/pgSQL) function is unnecessary. As Luc M has mentioned a view would be simplest and fastest.

If you insist on having a function though your next choice should be an SQL function - more info here and here.

Milen A. Radev