MySQL 通過預存程序簡化INSERT和UPDATE

來源:互聯網
上載者:User

MySQL 通過預存程序簡化INSERT和UPDATE

MySQL 通過預存程序簡化INSERT和UPDATE

處理目的,當資料表中存在目標記錄時,執行UPDATE;當資料表中不存在目標記錄時,執行INSERT;從而減少一次查詢資料庫的過程

預存程序設計如下:

CREATE PROCEDURE `pro_SaveData`(IN `sinst` varchar(500),IN `supdt` varchar(500))
BEGIN
 #直接更新記錄
    set @v_updsql=supdt; 
    prepare stmt from @v_updsql; 
    EXECUTE stmt;     
   
 #記錄不存在,執行INSERT
 IF ROW_COUNT() =0 THEN
   set @v_intsql=sinst;
    prepare stmt from @v_intsql;
    EXECUTE stmt;     
 END IF;
deallocate prepare stmt;   
END;

C#調用如下:

int r = data.ExecuteNonQuery(System.Data.CommandType.StoredProcedure,
                @"CALL pro_SaveData (' INSERT INTO `table` VALUES ('1', 'username')',
                'UPDATE table SET name='table222' WHERE id='1';')", null);

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.