Generate random name in Mysql - Stored Procedure

Asked

Viewed 1,627 times

0

Good evening, is there any way to generate random names with stored data in Mysql? I have the following table:

STUDENT(id:int[PK], name(varchar(100)), age: int, Cr(float))

I need to popular this table with 10,000 entries. To generate the random numbers I found the function RAND() Mysql, but found nothing related to random VARCHAR with Store Procedure.

  • 1

    Take a look at this one:http://thecodecave.com/downloads/NameGeneration.sql

2 answers

1


One way I found and not at all elegant was this:.

Use the function substring() together with the Rand() to select a letter randomly from all of the alphabet I passed as argument.
After that use the function Concat() to concatenate all letters into one.

delimiter $$
drop procedure if exists projBD.populaAluno $$
create procedure populaAluno()
begin   
declare nome varchar(100);
declare idade int ;
declare cr float;
declare counter int default 0;
while counter <= 10000 do
    set nome = concat(substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1)
            ) ;     
     set idade = floor(1 + (rand() * 99));
     set cr = rand()*10 ;
    insert into ALUNO (nome,idade,cr) 
    values (nome,idade,cr);
    set counter = counter + 1;
    end while;
End $$
delimiter ;

0

  • So, the exercise only mentioned inserting 10k random students using stored Procedure. It didn’t talk about entering data from outside. However, this is a great tool! I will save this link here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.