處理目的,當數據表中存在目標記錄時,執行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);