简体   繁体   中英

How to insert two or more records from a 'unique' field in MySql?

I have these tables

 CREATE TABLE persona( 
id INT PRIMARY KEY AUTO_INCREMENT,
 nombre VARCHAR(30),
 apPaterno VARCHAR(30), 
 ine VARCHAR(12) unique);
 
 CREATE TABLE cliente( cuenta INT PRIMARY KEY, 
 saldoapertura DOUBLE,
 fechaRegistro DATE, 
 sucursal VARCHAR(30), 
 idPersona int, 
 FOREIGN KEY(idPersona) REFERENCES persona(id));

It is about simulating a bank, in which the identification is unique for each person (ine), I want to know if there is a way to insert a person with different accounts several times. Even if the 'unique' clause exists in the (ine) field.

The stored procedure is this:

delimiter ##
 create procedure sp_aperturaCuenta(
    IN p_nombre varchar(30),
    in p_apellidoPaterno varchar (30),
    in p_ine varchar (12),
    in p_cuenta int,
    in p_saldoApertura double,
    in p_sucursal varchar (30)
 )
 begin
 declare id int;
 declare fallo boolean default  0; 
 declare continue handler for sqlexception
 begin
 set fallo = 1;
 end;
 start transaction;
 
 insert  into persona (nombre, apPaterno, ine) values (p_nombre,p_apellidoPaterno, p_ine);
    set id = last_insert_id();
    insert  into cliente values (p_cuenta,p_saldoApertura, curdate(), p_sucursal, id ); 
   
    if fallo = 0 then
    commit; 
    else
    rollback;
    end if;
 end ##
 delimiter ;

Here are the calls to the procedure:

Call sp_aperturaCuenta('Carlos','Montes','12302002120',1121,1000,'Delta'); 
Call sp_aperturaCuenta('Carlos','Montes','12302002120',1231,5000,'Delta');

As can be seen, the only difference between one call and another is that the account is different. And I can't insert the second.

To add a second cliente record for an existing persona , rename your id variable to v_id :

declare v_id int;

Then try to lookup the persona by ine and insert only if you cannot find a record.

    select id into v_id from persona where ine = p_ine;
    if v_id is null then 
      insert  into persona (nombre, apPaterno, ine) values (p_nombre,p_apellidoPaterno, p_ine);
      set v_id = last_insert_id();
    end if;
    insert  into cliente values (p_cuenta,p_saldoApertura, curdate(), p_sucursal, v_id ); 
    

The unique constraint is a constraint for a reason and RBDMs are excellent at following constraints .

As long as you have the unique constraint in your table definition, the column for which the unique constraint is defined for cannot have multiple equal values.

The only way to bypass the constraint is to remove it, which is not what I'm suggesting if it confronts the requirements for your DB design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM