dimanche 30 juillet 2017

Generate a random number betwen two numbers

I wrote the a procedure bellow:

DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`root`@`localhost` PROCEDURE `numerodasorte` (IN `id` INT, IN `cupons` INT)  begin

declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;

  while v_counter < cupons do
  INSERT INTO numerosorte (cupons_idcupons,numero) VALUES(id,
    (SELECT random_num  FROM ( SELECT floor(100000+RAND()*(599999-100000)) AS random_num ) AS numbers_mst_plus_1 WHERE random_num NOT IN (SELECT numero FROM cupons WHERE numero IS NOT NULL) LIMIT 1)) ;
    /*
    INSERT INTO numerosorte(cupons_idcupons,numero) VALUES(id,numero);
    */
    set v_counter = v_counter + 1;
  end while;
SELECT cupons_idcupons,numero FROM numerosorte WHERE cupons_idcupons=id;

end$$

Based on this post:

How to Generate Random number without repeat in database using PHP?

but when i run this[ SET @p0='6'; SET @p1='200'; CALL numerodasorte(@p0, @p1); ] , sometimes, i get this error:

1062 - Duplicated entry '27397' for key 'numero_UNIQUE'

Someone have any ideia whats is happening?




Aucun commentaire:

Enregistrer un commentaire