title: MySql Stored Procedure : Get Last Inserted Id
body: <p>My Procedure :</p>
  
  <pre><code>DELIMITER $$
  
  CREATE PROCEDURE `******`.`*********************` 
  (   IN customerName varchar(100),IN customerEmail varchar(100),IN address1 varchar(100),IN address2 varchar(100),
      IN zip int,IN city varchar(100),IN state varchar(100),IN country varchar(100),IN region varchar(100),OUT customerId int)
  BEGIN
  
  Declare custId int default 0;
  Declare zipExist int default 0;
  
  Select Count(*) into zipExist from *****.********** where Zip_Code = zip;
  
  if zipExist = 0 then
  Insert into *****.**********(Zip_Code,City,State,Country,Region) values(zip,city,state,country,region); 
  end if;
  
  Insert into *****.**********(Address_1,Address_2,ZIP_Code) values(address1,address2,zip);
  
  SET custId = LAST_INSERT_ID();
  
  if custId &gt; 0 then
  Insert into *****.**********(Customer_Name,Customer_Email,Address) values(customerName,customerEmail,custId);
  end if;
  
  SET customerId = LAST_INSERT_ID();
  END $$
  </code></pre>
  
  <p>on calling the procedure I am getting this error:
  Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'</p>
  
  <p>I am assuming that <code>custId= Last_Insert_Id();</code> this line is giving me wrong inserted id. hence it is not able to insert into last table.
  I would like to know how to get  last inserted id after insert.(Address_id is auto-increment).   </p>
  
  <p>tables are :   </p>
  
  <p><strong>Customer:</strong><br>
  CustomerId int auto-increment,<br>
  CustomerName varchar,<br>
  CustomerEmail varchar,<br>
  AddressId int fk references address.AddressId  </p>
  
  <p><strong>Address :</strong>    </p>
  
  <p>AddressId pk int auto-increment,<br>
  Address1 varchar,<br>
  Address2 varchar,<br>
  zip int fk references zipmaster.zip  </p>
  
  <p><strong>zipmaster :</strong>  </p>
  
  <p>zip int pk auto-increment,<br>
  city varchar,<br>
  state varchar,<br>
  country varchar  </p>