Created
May 8, 2012 18:53
-
-
Save iamvery/2638462 to your computer and use it in GitHub Desktop.
PostgreSQL function that safely casts a string value to an integer. Useful when sorting string fields as numbers :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Function: "Safe_Cast_Str_to_Int"(character varying, integer) | |
CREATE OR REPLACE FUNCTION "Safe_Cast_Str_to_Int"(input_string character varying, default_value integer DEFAULT NULL::integer) | |
RETURNS integer AS | |
$BODY$ | |
BEGIN | |
BEGIN | |
RETURN input_string::integer; | |
EXCEPTION WHEN data_exception THEN | |
RETURN default_value; | |
END; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE | |
COST 100; | |
ALTER FUNCTION "Safe_Cast_Str_to_Int"(character varying, integer) OWNER TO postgres; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment