patternsqlMinor
Select in a PostgreSQL function
Viewed 0 times
postgresqlselectfunction
Problem
I'm trying to do my first Function in PostgreSQL, but I can't to do it.
I was write this piece of code
But... The error is when I'm trying to call taht function:
Where is the issue?
the error message it's:
Thanks in advance!
I was write this piece of code
CREATE OR REPLACE FUNCTION getCars ()
RETURNS TABLE (
car_name VARCHAR,
id_car INT
)
AS $
BEGIN
RETURN QUERY SELECT
brand,car_id
FROM
cars;
end;
$
LANGUAGE plpgsql;But... The error is when I'm trying to call taht function:
SELECT getcars();Where is the issue?
the error message it's:
SQL Error [42804]: ERROR: structure of query does not match function result type
Detail: Returned type text does not match expected type character varying in column 1.
Where: PL/pgSQL function getcars() line 3 at RETURN QUERYThanks in advance!
Solution
You have two errors:
So you need to change your function definition to:
And then use it like this:
Simple functions that just return a query are better defined as
- apparently
brandis defined astext, notvarchar
- set returning functions have to be used like a table in the
FROMclause.
So you need to change your function definition to:
CREATE OR REPLACE FUNCTION getcars()
RETURNS TABLE (car_name text, id_car INT)
AS $
BEGIN
RETURN QUERY
SELECT brand,car_id
FROM cars;
end;
$
LANGUAGE plpgsql;And then use it like this:
select *
from getcars();Simple functions that just return a query are better defined as
language sql:CREATE OR REPLACE FUNCTION getcars()
RETURNS TABLE (car_name text, id_car INT)
AS $
SELECT brand,car_id
FROM cars;
$
LANGUAGE sql
stable;Code Snippets
CREATE OR REPLACE FUNCTION getcars()
RETURNS TABLE (car_name text, id_car INT)
AS $$
BEGIN
RETURN QUERY
SELECT brand,car_id
FROM cars;
end;
$$
LANGUAGE plpgsql;select *
from getcars();CREATE OR REPLACE FUNCTION getcars()
RETURNS TABLE (car_name text, id_car INT)
AS $$
SELECT brand,car_id
FROM cars;
$$
LANGUAGE sql
stable;Context
StackExchange Database Administrators Q#244553, answer score: 4
Revisions (0)
No revisions yet.