PGSQL error for If statement in function - postgresql

I'm trying to create a function for pgsql where I need to return a boolean if an equipment exists in a lecture hall. I'm getting the following error:
"ERROR: return type mismatch in function declared to return boolean"
"DETAIL: Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING."
CREATE FUNCTION hasProjector(int) RETURNS boolean AS $$
DO
$do$
BEGIN
IF EXISTS(SELECT * FROM LectureRoomEquipment WHERE LectureRoomID = $1 AND EquipmentID = 1) THEN
SELECT true AS hasProjector;
ELSE
SELECT false AS hasProjector;
END IF;
END
$do$
$$ LANGUAGE SQL;
Does anyone advise me what i'm doing wrong and how I can fix this? Thank you.

You don't need plpgsql. Do it as plain SQL
create function hasprojector(int) returns boolean as $$
select exists (
select *
from lectureroomequipment
where lectureroomid = $1 and equipmentid = 1
);
$$ language sql;

Related

Query has no destination for result data when try to make search filter [duplicate]

I am trying to fetch data from remote db by using dblink through function but getting an error "query has no destination for result data". I am using plpgsql language to do the same.
Function:
CREATE OR REPLACE FUNCTION fun()
RETURNS text AS
$$
begin
select dblink_connect(
'port=5432 dbname=test user=postgres password=****');
WITH a AS (
SELECT *
FROM dblink(
'SELECT slno,fname,mname,lname
FROM remote_tbl'
) AS t (slno int, fname text, mname text, lname text)
)
, b AS (
INSERT INTO temptab1
SELECT slno, name
FROM a
)
, c AS (
INSERT INTO temptab2
SELECT slno, name
FROM a
)
INSERT INTO temptab3
SELECT slno, name
FROM a;
select dblink_disconnect();
end;
$$
LANGUAGE plpgsql;
Calling Function:
select fun();
Error: query has no destination for result data
The stored procedure won't just return the result of the last SELECT. You need to actually return the value:
CREATE OR REPLACE FUNCTION fun() RETURNS text AS $$
BEGIN
--- ....
RETURN(SELECT dblink_disconnect());
END
$$ LANGUAGE plpgsql;
You're getting the error because Postgres expects the function to return something of type text, but your function doesn't return anything.
Use a plain SQL function instead of PL/PgSQL, or use SELECT INTO and ordinary RETURN.
Reason for the error you're getting is because there is no return in between your BEGIN and END for example:
BEGIN
update mytable set lastcodeused = to_char(cast(lastcodeused as INTEGER)+1, 'FM999999999999999999') where
classid = classIdVar and appid= appIdInt
RETURNING concat(pageUniqueCode,lastcodeused) as pageUniqueCode
into taskcode;
return taskcode;
END;
If you have this error using a pgplsql procedure or function, and you are sure that the return is defined correctly, there exists a different non-intuitive cause. I needed some time to realize this so I think it is worth sharing. I had a function like this:
CREATE OR REPLACE FUNCTION "db".fn_x(
id integer)
RETURNS TABLE(b_val varchar(100), c_val varchar(100))
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
var_b_val varchar(100);
var_c_val varchar(100);
BEGIN
select var_b, var_c
-- Missing INTO clause was the cause of the error.
var_b_val, var_c_val
from "db".table_y where y_id = id;
return query(select var_b_val, var_c_val);
END;
$BODY$;
Just adding that missing INTO clause made the function work correctly.
In conclusion, this error can also trigger on silent syntax errors.

How to run SELECT queries in PL/pgSQL IF statements

I am trying to run SELECT queries in PL/pgSQL IF statements using the code below:
DO
$do$
DECLARE
query_type real;
arr real[] := array[1];
BEGIN
IF query_type = 1 THEN
RETURN QUERY
SELECT "Westminster".*
FROM "Westminster"
WHERE ("Westminster".intersects = false AND "Westminster".area <= 100);
ELSE IF query_type = 0 THEN
RETURN QUERY
SELECT "Westminster".*
FROM "Westminster";
END IF;
END
$do$
However I get the following error, ERROR: cannot use RETURN QUERY in a non-SETOF function.
Does anyone know how I can get the above code to work? Thank you.
UPDATE: This ended up working for me:
CREATE OR REPLACE FUNCTION my_function(query_type integer)
RETURNS SETOF "Westminster" LANGUAGE plpgsql as $$
BEGIN
IF query_type = 1 THEN
RETURN QUERY
SELECT "Westminster".*
FROM "Westminster"
WHERE ("Westminster".intersects = false AND "Westminster".area <= 100);
ELSIF query_type = 0 THEN
RETURN QUERY
SELECT "Westminster".*
FROM "Westminster";
END IF;
END;
$$;
I then called the function like this:
SELECT * FROM my_function(1);
From the documentation:
The code block is treated as though it were the body of a function with no parameters, returning void.
You can use RETURN QUERY only in a function returning SETOF <type> or TABLE(...). Use the table "Westminster" as the resulting type, e.g.:
CREATE OR REPLACE FUNCTION my_function(query_type int)
RETURNS SETOF "Westminster" LANGUAGE plpgsql as $$
BEGIN
IF query_type = 1 THEN
RETURN QUERY
SELECT "Westminster".*
FROM "Westminster"
WHERE ("Westminster".intersects = false AND "Westminster".area <= 100);
ELSIF query_type = 0 THEN
RETURN QUERY
SELECT "Westminster".*
FROM "Westminster";
END IF;
END;
$$;
-- exemplary use:
SELECT * FROM my_function(1);
Note the proper use of ELSIF.
I don't think anonymous code blocks support it. Try creating a function and defining its resultset to table, e.g:
CREATE OR REPLACE FUNCTION myfunc() RETURNS TABLE (val INT) AS $$
BEGIN
RETURN QUERY SELECT 1;
END;
$$ LANGUAGE plpgsql;
To call your function you could use:
SELECT * FROM myfunc();
Note: keep in mind that the table declared on the function's header needs to have the same fields returned in the RETURN QUERY statement.

PostgreSQL 9.3: isnumeric() in a condition

I need to check whether the given text is numeric or not from the
function.
Creating function for isnumeric():
CREATE OR REPLACE FUNCTION isnumeric(text) RETURNS BOOLEAN AS $$
DECLARE x NUMERIC;
BEGIN
x = $1::NUMERIC;
RETURN TRUE;
EXCEPTION WHEN others THEN
RETURN FALSE;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
Function from which I am calling the isnumeric() function:
create or replace function tm(var text)
returns varchar as
$$
begin
if (select isnumeric(var))=t::BOOLEAN then
raise info 'Is numeric value';
else
raise info 'Not numeric';
end if;
end;
$$
language plpgsql;
Calling functon:
select tm('1');
Getting an error:
Here is the error details:
ERROR: column "t" does not exist
LINE 1: SELECT (select isnumeric(var))=t::BOOLEAN
You don't need a select (and it's actually wrong, as the error indicates) - just call isnumeric directly.
Also, by the way, your function is missing a return statement.
To sum it all up:
create or replace function tm(var text)
returns varchar as
$$
begin
if (isnumeric(var)) then -- call isnumeric directly
raise info 'Is numeric value';
else
raise info 'Not numeric';
end if;
return '0'; -- missing return value in the OP
end;
$$
language plpgsql;
this will help you to identify your field is numeric or not:
select * from Table where field_name ~ '^[0-9]*$'
for decimal values you can use^[0-9.]*$ instead ^[0-9]*$
select getDataType('2021'); == Number
select getDataType('2021-05-12 23:12:10'); == Date
select getDataType('2021-05-12'); == Date
select getDataType('2X'); == String
CREATE
OR REPLACE FUNCTION getDataType ( TEXT ) RETURNS TEXT AS $$ DECLARE
x VARCHAR;
BEGIN
x = $1 :: NUMERIC;
RETURN 'Number';
EXCEPTION
WHEN OTHERS THEN
BEGIN
x = $1 :: DATE;
RETURN 'Date';
EXCEPTION
WHEN OTHERS THEN
RETURN 'String';
END;
END;
$$ STRICT LANGUAGE plpgsql IMMUTABLE;

PostgreSQL: Query has no destination for result data

I am trying to fetch data from remote db by using dblink through function but getting an error "query has no destination for result data". I am using plpgsql language to do the same.
Function:
CREATE OR REPLACE FUNCTION fun()
RETURNS text AS
$$
begin
select dblink_connect(
'port=5432 dbname=test user=postgres password=****');
WITH a AS (
SELECT *
FROM dblink(
'SELECT slno,fname,mname,lname
FROM remote_tbl'
) AS t (slno int, fname text, mname text, lname text)
)
, b AS (
INSERT INTO temptab1
SELECT slno, name
FROM a
)
, c AS (
INSERT INTO temptab2
SELECT slno, name
FROM a
)
INSERT INTO temptab3
SELECT slno, name
FROM a;
select dblink_disconnect();
end;
$$
LANGUAGE plpgsql;
Calling Function:
select fun();
Error: query has no destination for result data
The stored procedure won't just return the result of the last SELECT. You need to actually return the value:
CREATE OR REPLACE FUNCTION fun() RETURNS text AS $$
BEGIN
--- ....
RETURN(SELECT dblink_disconnect());
END
$$ LANGUAGE plpgsql;
You're getting the error because Postgres expects the function to return something of type text, but your function doesn't return anything.
Use a plain SQL function instead of PL/PgSQL, or use SELECT INTO and ordinary RETURN.
Reason for the error you're getting is because there is no return in between your BEGIN and END for example:
BEGIN
update mytable set lastcodeused = to_char(cast(lastcodeused as INTEGER)+1, 'FM999999999999999999') where
classid = classIdVar and appid= appIdInt
RETURNING concat(pageUniqueCode,lastcodeused) as pageUniqueCode
into taskcode;
return taskcode;
END;
If you have this error using a pgplsql procedure or function, and you are sure that the return is defined correctly, there exists a different non-intuitive cause. I needed some time to realize this so I think it is worth sharing. I had a function like this:
CREATE OR REPLACE FUNCTION "db".fn_x(
id integer)
RETURNS TABLE(b_val varchar(100), c_val varchar(100))
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
var_b_val varchar(100);
var_c_val varchar(100);
BEGIN
select var_b, var_c
-- Missing INTO clause was the cause of the error.
var_b_val, var_c_val
from "db".table_y where y_id = id;
return query(select var_b_val, var_c_val);
END;
$BODY$;
Just adding that missing INTO clause made the function work correctly.
In conclusion, this error can also trigger on silent syntax errors.

Create Operator In Postgresql

Anyone knows how to call self defined operator in postgresql?
I hava the following operator:
CREATE OR REPLACE FUNCTION algo.fun_temp(IN exp BOOLEAN)
RETURNS INTEGER AS $$
BEGIN
RETURN NOT exp;
END;
$$ LANGUAGE plpgsql;
CREATE OPERATOR algo.~
(
PROCEDURE = algo.fun_temp,
RIGHTARG = BOOLEAN
);
And when I try to call this operator with SELECT algo.~ TRUE, the client complains
"ERROR: syntax error at or near "~"
LINE 1: SELECT algo.~ TRUE"
Anyone knows what the problem is? Any help is appreciated.
cheng
The function should return INTEGER, what you wrote returns BOOLEAN:
CREATE OR REPLACE FUNCTION algo.fun_temp(IN exp BOOLEAN)
RETURNS INTEGER AS $$
BEGIN
RETURN (NOT exp)::INTEGER;
END;
$$ LANGUAGE plpgsql;
Then add the schema algo to the search_path:
SET search_path = public, algo;