I have the CONV function in Mysql:
mysql> CONV(26,10,26)
-> 10
But I want something like this:
mysql> CONV_LETTERS(26,10,26)
-> aa
How can I convert in MySQL from base 10 to base 26, but only use letters so that number 26 will become aa?
UPDATE
I got so far:
delimiter //
CREATE PROCEDURE `base10_to_base26_letters`(IN `nr` BIGINT)
BEGIN
SET @letters='abcdefghijklmnopqrstuvwxyz';
select SUBSTRING(@letters,`nr`+1,1);
END//
UPDATE 2
Trying to convert this php function to MySQL procedure.
The PHP function:
function generateAlphabet($na) {
$sa = "";
while ($na >= 0) {
$sa = chr($na % 26 + 65) . $sa;
$na = floor($na / 26) - 1;
}
return $sa;
}
My MySQL procedure so far:
delimiter //
CREATE PROCEDURE `base10_to_base26_letters`(IN `nr` BIGINT)
BEGIN
SET @n=`nr`,@letters='abcdefghijklmnopqrstuvwxyz',@r='';
while @n>=0 do
set @n=@n/26-1,@r=concat(SUBSTRING(@letters,@n%26,1),@r);
end while;
select @r;
END//
Why I only get z for any number I tried?
This stored function converts a single int to base26:
DROP FUNCTION IF EXISTS `base10to26`;
DELIMITER ;;
CREATE FUNCTION `base10to26`(`theNumber` INT(11) UNSIGNED)
RETURNS VARCHAR(20) READS SQL DATA
BEGIN
DECLARE colTxt VARCHAR(20);
DECLARE value INT(11);
SET colTxt = '';
REPEAT
SET value = theNumber % 26;
IF value = 0 THEN SET value = 26; END IF;
SET theNumber = (theNumber - value) / 26;
SET colTxt = CONCAT(CHAR(value+64), colTxt);
UNTIL theNumber = 0 END REPEAT;
RETURN colTxt;
END;;
DELIMITER ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With