Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert random numbers MySql

Tags:

mysql

Im new to MySql, and I need to insert into table 10000 random 2-digit numbers. Is there Easy way to to this?

like image 691
el ninho Avatar asked Mar 29 '12 14:03

el ninho


2 Answers

Use RAND() as described here. For generating 2-digit random numbers between 10 and 99, use FLOOR(10 + (RAND() * 90)).

like image 192
nikhil500 Avatar answered Sep 29 '22 18:09

nikhil500


Try this:

DELIMITER $$
CREATE PROCEDURE random_fill( IN cnt INT )
BEGIN

    fold: LOOP

         IF cnt < 1 THEN
             LEAVE fold;
         END IF;

        INSERT INTO foo ( bar ) VALUES ( 9 + CEIL( RAND() * 90 ) );

        SET cnt = cnt - 1;
    END LOOP fold;

END$$   
DELIMIMTER ;

To use this:

CALL random_fill(10000);

What you have to change is this line:

INSERT INTO foo ( bar ) VALUES ( CEIL( RAND() * higher ) );

Replace the foo and bar with something that exists in your database. It is possible to create a procedure, where the name of table and row are also supplied as parameters, but that would require to CONCAT the query on fly .. looks hack'ish and ugly.

like image 29
tereško Avatar answered Sep 29 '22 16:09

tereško