This work for me in MYSQL:
FUNCTION leadingZero(format VARCHAR(255), num VARCHAR(255))
RETURNS varchar(255) CHARSET utf8
BEGIN
return CONCAT(SUBSTRING(format,1,LENGTH(format)-LENGTH(num)),num);
END
For example:
leadingZero('000',999); returns '999'
leadingZero('0000',999); returns '0999'
leadingZero('xxxx',999); returns 'x999'
Hope this will help. Best regards