title: Logic condition to avoid duplicate entries in stored procedure
body: <p>I have the following stored procedure . I'm trying to insert the users from the table usuaris, whose admin variable is equal to 1, into the table that the stored procedure creates with the name( <code>nombre varchar(50)</code>) that is passed as a parameter.</p>
  
  <p>When the procedure is called, it duplicates the user 'mary' with <code>id</code> 4. I've tried a couple of ways to implement the logic condition in order to avoid the duplication, but still, I'm missing something and I can't get the desired result. In the code below, the logic condition before the insertion is the last thing I've tried. Any ideas?</p>
  
  <p>Thanks.   </p>
  
  <pre><code> CREATE DEFINER=`root`@`localhost` PROCEDURE `createNewtable`(nombre varchar(50))
   BEGIN
  
   /*variable declaration*/
  
   declare centinela int ;
   declare id1 int ;
   declare nom1 varchar(50);
   declare admin1 enum('0','1') ;
  
   declare cadena varchar(100);    /*string to concatenate table creation and insertion*/
  
  
   /*cursor declaration*/
  
   declare cursor1 cursor for select * from users.usuaris where admin = '1' ;
   declare continue handler for not found set @centinela = 1 ;
  
  
    /*create the table with the name that's passed as parameter*/
  
    set @cadena=concat("create table ",nombre,                 
                 "(
                   id2 int not null primary key,
                   nom2 varchar(50),
                   admin2 enum ('0','1')
                   )" );
  
     prepare stmt from @cadena ;
     execute stmt ;
     deallocate prepare stmt;
  
  
  /* loop that fetches the data from the table usuaris and 
   inserts them into the newly created table. */
  
    set @centinela = 0 ;
    open cursor1 ;
  
    bucle: loop
       fetch cursor1 into id1,nom1,admin1 ;
  
     if ( centinela = 1 ) then
      leave bucle ;
         end if ;
  
         /*logic condition to avoid entry duplication */
  
         if not exists (select * from users.usuaris where admin='1' and id=@id1) then
           set @cadena=concat("insert into ",nombre," values( ",id1,",'",nom1,"','",admin1,"')");
         end if;
  
        select @cadena;
        prepare stmt from @cadena;
        execute stmt ;
        deallocate prepare stmt;
  
    end loop bucle;
    close cursor1;
  
  END
  </code></pre>
  
  <p>Here is the  single-table database of users :</p>
  
  <pre><code> create database if not exists `users` ;
  
   use  `users` ;
  
   create table usuaris(
  
    id int not null auto_increment primary key ,
    nom varchar(50),
    admin enum ('0','1')
  
    );
  
  
    insert into  usuaris(id,nom,admin)
    values 
         (1,'jose','1'),
         (2,'maria','0'),
         (3,'frank','1'),
         (4,'mary','1'),
         (5,'godfrey','0') ;
  </code></pre>