Update if record already exist else insert-MySQL

I am uploading an excel file into the database table,

What I want is, If any record from excel sheet already exists into the table then update that record with the latest data which is available on the sheet.

How to do that?

Well,

It is pretty simple

Following is the syntax to perform that query:

IF EXISTS (SELECT Col1,Col2,Col3 FROM TheTable WHERE Col1 = ExcelCol AND Col2 = ExcelCol2 AND ....)
  BEGIN
    --Update Query
  END
ELSE
  BEGIN
    -- Insert Query
  END
/*Here is the complete example using stored Procedure*/
DELIMITER $$

USE `db_name`$$

DROP PROCEDURE IF EXISTS `upd_if_exist`$$

CREATE DEFINER=`admin`@`%` PROCEDURE `upd_if_exist`(
  Vid_name VARCHAR (1000),
  Vid_number VARCHAR(200),
  Vcity VARCHAR (1000),
  Vprovince VARCHAR (1000),
  Vevent_date VARCHAR(200),
  Vstart_time VARCHAR(200),
  Vend_time  VARCHAR(200),
  Vplace VARCHAR (2000),
  Vaddress VARCHAR(2000))
   
COMMENT 'Add or Edit Event'
    
BEGIN
IF EXISTS(SELECT id_number,event_date FROM all_events WHERE id_number=Vid_number AND event_date=Vevent_date) THEN	
  UPDATE power_tour_events SET 
  id_name=Vid_name,city=Vcity,province=Vprovince,start_time=Vstart_time,end_time=Vend_time,place=Vplace,
  address=Vaddress WHERE (id_number=Vid_number AND event_date=Vevent_date);
  ELSE
  INSERT INTO `power_tour_events` (
    dealer_name,
    dealer_number,
    city,
    province,
    event_date,
    start_time,
    end_time,
    place,
    address
  )
  VALUES
    (
      Vdealer_name,
      Vdealer_number,
      Vcity,
      Vprovince,
      Vevent_date,
      Vstart_time,
      Vend_time,
      Vplace,
      Vaddress);
END IF;
 END$$

DELIMITER ;

39 thoughts on “Update if record already exist else insert-MySQL

  1. Pingback: Abzocke
  2. Pingback: English Bread
  3. Pingback: thatstamil
  4. Pingback: Goedkoop Taxi
  5. Pingback: online business
  6. Pingback: chip card pos
  7. Pingback: kona coffee
  8. Pingback: kona coffee
  9. Pingback: kona coffee
  10. Pingback: kona coffee
  11. Pingback: kona coffee
  12. Pingback: biyougeka
  13. Pingback: empanada wikipedia
  14. Pingback: Phone cases
  15. Pingback: beauty tips
  16. Pingback: vape starter kit
  17. Pingback: modern designer
  18. Pingback: Mental health
  19. Pingback: Bachatero
  20. Pingback: bts merchandise
  21. Pingback: canal infantil
  22. Pingback: PD Blower
  23. Pingback: medium
  24. Pingback: czyszczenie strony
  25. Pingback: Games golf

Leave a Reply