8

Duplicate:
Inserting random characters to MYSQL Database

How can I generate 100 records with 5 random characters and insert into the database with a query.

I want to insert into this table:

codes
  id (auto-increment)
  codes
0

4 Answers 4

18

Try this one -

SELECT CONCAT(
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25)))
  ) random_string;

This query generates ASCII codes from 'A' to 'Z' and generates a random string from them. I cannot say that this way is elegant, but it works;-)

8
INSERT INTO codes_tbl (codes) VALUES (SUBSTRING(MD5(RAND()) FROM 1 FOR 5));

That should take care of it.

3
  • 4
    Except that md5 gives you a string that only includes hex digits so the codes will be quite limited. Commented Nov 21, 2011 at 5:05
  • 1
    hello, i cannot run the code. got an error. 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 1 Commented Nov 21, 2011 at 5:08
  • 1
    There is an issue with the parentheses:INSERT INTO codes_tbl (codes) VALUES (SUBSTRING(MD5(RAND()) FROM 1 FOR 5));
    – Nate
    Commented Sep 14, 2016 at 17:27
0

In MySql U Can Do It Like This

insert into table ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , .........

If You Want to Do it With Php. U Can Check This Link

Further You can Check The Following Questions Already asked at Stackoverflow

1. Random Number- MySql

2. Mysql insert random unique 8 chars

0

Could you try this out?:

CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertOneHundredRandomCodes` ()
BEGIN
    DECLARE ctr INT DEFAULT 0;
    hundred_loop:LOOP
        SET ctr = ctr + 1; -- increment
        -- insert command here
        INSERT INTO codes (codes)
        SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 5) AS codes;
        IF ctr = 100 THEN -- check if we should stop
            LEAVE hundred_loop;
        END IF;
    END LOOP hundred_loop;
END//

Create that procedure then run this command:

CALL InsertOneHundredRandomCodes();

It should insert into codes 100 random values for the codes value.

Not the answer you're looking for? Browse other questions tagged or ask your own question.