Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 431
MAK Avatar asked Jan 27 '15 06:01

MAK


1 Answers

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;
like image 62
Mureinik Avatar answered Sep 30 '22 19:09

Mureinik