Skip to content

Instantly share code, notes, and snippets.

@chanmix51
Created March 19, 2010 20:22
Show Gist options
  • Save chanmix51/338134 to your computer and use it in GitHub Desktop.
Save chanmix51/338134 to your computer and use it in GitHub Desktop.
Smart substring in plpgsql
CREATE OR REPLACE FUNCTION cut_nicely(my_string VARCHAR, my_length INTEGER) RETURNS varchar AS $$
DECLARE
my_pointer INTEGER;
BEGIN
my_pointer := my_length;
WHILE my_pointer < length(my_string) AND transliterate(substr(my_string, my_pointer, 1)) ~* '[a-z]' LOOP
my_pointer := my_pointer + 1;
END LOOP;
RETURN substr(my_string, 1, my_pointer);
END;
$$ LANGUAGE plpgsql
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment