I'm trying to get a random string in phpmyadmin using a function. I have the following code:
CREATE FUNCTION randomPassword()
RETURNS varchar(128)
BEGIN
SET @chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
SET @charLen = length(@chars);
SET @randomPassword = '';
WHILE length(@randomPassword) < 12
SET @randomPassword = concat(@randomPassword, substring(@chars,CEILING(RAND() * @charLen),1));
END WHILE;
RETURN @randomPassword ;
END;
Now I get the error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5
Does anyone know how I can fix this?
If you need a string of random digits up to 32 characters for test data or just need some junk text to fill a field, SQL Server's NEWID() function makes this simple. NEWID() is used to create a new GUID (globally unique identifier), and we can use that as a base to get a string of random characters.
UUID() function in MySQL. This function in MySQL is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, “A Universally Unique Identifier (UUID) URN Namespace”. It is designed as a number that is universally unique.
Random Integer RangeSELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for. SELECT FLOOR(RAND()*(25-10+1))+10; The formula above would generate a random integer number between 10 and 25, inclusive.
This is faster than concat
+ substring
routine.
select substring(MD5(RAND()),1,20);
As I've tested inserting 1M random data, md5
routine consumes only 1/4 (even less) time of concat
+ substring
routine;
The problem is a md5 string contains only 32 chars so if you need a longer one you'd have to manually generate more md5 strings and substring
it yourself.
Try this more simple solution:
SELECT CONV(FLOOR(RAND() * 99999999999999), 10, 36)
SELECT SUBSTRING(REPLACE(REPLACE(REPLACE( TO_BASE64(MD5(RAND())), '=',''),'+',''),'/',''), 2, 40)
This solution to generate a fixed length random string that contains all lower- and upper-case chars and digits.
SELECT SUBSTRING(REPLACE(REPLACE(REPLACE( TO_BASE64(MD5(RAND())), '=',''),'+',''),'/',''), 2, FLOOR(10+RAND()*31))
If you need a random length string (from 10 to 40 symbols in this example)
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