Created
December 30, 2011 13:22
-
-
Save robcowie/1539835 to your computer and use it in GitHub Desktop.
Postgresql function to generate unique alpha-numeric codes
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
-- Actually, if UNIQUE is defined on the col, there is no need to store previous codes | |
-- It will fail to insert due to uniqueness contraint when all possible codes are exhausted | |
-- Use as a column default... | |
-- CREATE TABLE foo (id CHAR(6) DEFAULT AlphaNumericSerial() UNIQUE); | |
CREATE OR REPLACE FUNCTION AlphaNumericSerial() | |
RETURNS char(6) AS $$ | |
DECLARE _serial char(6); _i int; _chars char(36) = 'abcdefghijklmnopqrstuvwxyz0123456789'; | |
BEGIN | |
_serial = ''; | |
FOR _i in 1 .. 6 LOOP | |
_serial = _serial || substr(_chars, int4(random() * length(_chars)), 1); | |
END LOOP; | |
RETURN lower(_serial); | |
END; | |
$$ LANGUAGE plpgsql VOLATILE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good, thanks guys