I want to CREATE CAST a suitable function to convert 'character varying' to 'integer'. Can anyone suggest a function? Everything I try fails.
-
5You should fix your SQL to not rely in implict casts. Do not rely on implict casts in your statements, never.user330315– user3303152011-01-21 15:54:13 +00:00Commented Jan 21, 2011 at 15:54
-
I agree. However I cannot I'm using a off-the-shelf piece of software.Simon– Simon2011-01-21 15:59:06 +00:00Commented Jan 21, 2011 at 15:59
4 Answers
Use this:
CREATE CAST (varchar AS integer) WITH INOUT [AS IMPLICIT];
It uses the input/output functions of the data types involved.
1 Comment
The function above works if you update your SQL to do an explicit cast. However, if you add 'as implicit' to the end of your "create cast" statement, Postgres will be able to automatically figure out what you are trying to do when you compare an integer with a varchar that can be converted to an integer.
Here is my updated statement that seemed to work "implicitly":
CREATE FUNCTION toint(varchar)
RETURNS integer
STRICT IMMUTABLE LANGUAGE SQL AS
'SELECT cast($1 as integer);';
CREATE CAST (varchar AS integer) WITH FUNCTION toint(varchar) as Implicit;
1 Comment
I assume you want to get back the behaviour of Postgres 8.3 regarding implicit casting.
See this blog entry for examples:
http://petereisentraut.blogspot.com/2008/03/readding-implicit-casts-in-postgresql.html
Oh: and bug that vendor of the software to fix the broken SQL ;)
Edit
This should do it:
CREATE FUNCTION toint(varchar) RETURNS integer STRICT IMMUTABLE LANGUAGE SQL AS 'SELECT cast($1 as integer);'; CREATE CAST (varchar AS integer) WITH FUNCTION toint(varchar);