Martin
Martin

Reputation: 165

How to return multiple default-values, when no results found in postgres?

I have the following function on a postgres-database:

CREATE OR REPLACE FUNCTION getNearestPoints(float[], float[], float[], float[], int)       
                    RETURNS SETOF record AS $$                                                                      
                DECLARE                                                                                             
                    i INT;                                                                                          
                    ret RECORD;     
                BEGIN                                                                                               
                    FOR i IN 1..$5 LOOP                                                                             
                         FOR ret IN EXECUTE 'SELECT height, ST_Y(point), ST_X(point)  FROM heights                   
                         WHERE ST_Intersects(ST_MakeEnvelope(' || $1[i] || ','  || $2[i] || ',' || $3[i] || ',' || $4[i] || ', 4326), point)' LOOP 
                         RETURN NEXT ret;                                                                           
                         END LOOP;                                                                                  
                    END LOOP;                                                                                       
                    RETURN;                                                                                         
                END;                                                                                                
                $$ LANGUAGE plpgsql;  

I want to return default values to the record for each column (e.g. (-2000, -181, -181)), if the query returns no rows.

Coalesce with records doesn't seem to be possible.

How can I manage to do this?

Upvotes: 0

Views: 348

Answers (1)

Wojtas
Wojtas

Reputation: 2354

If nothing was found then before RETURN you can assign values to the variable ret:

...
if not found then
    ret = row(-2000::integer, -181::integer, -181::integer);
    return next ret;
end if;

return;
...

Make sure that types used with row - "::integer" are the same as those in:

SELECT height, ST_Y(point), ST_X(point)  FROM heights

Upvotes: 1

Related Questions