mysql 判断是否已存在及插入表数据 的 简单存储过程

处理思路:
1、查找判断 相同数据是否已存在
2、如不存在,则执行Insert操作


CREATE PROCEDURE `mysql_sp_insert_data`(
  IN p_TableName varchar(100)   --表名
, IN p_ColumnNames varchar(200) --字段组合 ,以","分隔
, IN p_ColumnDatas varchar(500) --数据组成 ,以"@"分隔
)
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
   declare tmpExistDataCount int(4);
   declare tmpWhere varchar(800);
   declare tmpSqlStr varchar(1000);
   declare tmpSqlToRun varchar(2000);
   declare tmpSplitName varchar(10);
   declare tmpSplitData varchar(10);
   declare tmpNames varchar(800);
   declare tmpDatas varchar(800);
   declare tmpIndexName int(4);
   declare tmpIndexData int(4);
  
 set tmpNames = p_ColumnNames;
 set tmpDatas = p_ColumnDatas;
 set tmpSplitName = ",";
 set tmpSplitData = "@";
 
 set tmpWhere = " where 1 = 1 ";
 
select INSTR(tmpNames,tmpSplitName) into tmpIndexName;
 
if tmpIndexName > 0  then

 while tmpIndexName > 0 do
    select INSTR(tmpNames,tmpSplitName) into tmpIndexName;
    select INSTR(tmpDatas,tmpSplitData) into tmpIndexData;
  
    set tmpWhere = concat(tmpWhere , " and " , SUBSTRING(tmpNames,1,tmpIndexName -1) ," = ");
    set tmpWhere = concat(tmpWhere , SUBSTRING(tmpDatas,1,tmpIndexData -1 ) );
    
    
    set tmpNames = SUBSTRING(tmpNames,tmpIndexName + 1,LENGTH(tmpNames) - tmpIndexName);
    set tmpDatas = SUBSTRING(tmpDatas,tmpIndexData + 1,LENGTH(tmpDatas) - tmpIndexData);

    select INSTR(tmpNames,tmpSplitName) into tmpIndexName;

 end while;

end if;
 
  if LENGTH(tmpNames) > 0 then
     set tmpWhere = concat(tmpWhere , " and " , tmpNames ," = ");
     set tmpWhere = concat(tmpWhere , tmpDatas );
  end if;

   set tmpSqlStr = " select count(*) ";
   set tmpSqlStr = concat(tmpSqlStr  ," from  ", p_TableName ,tmpWhere , "  ; "  );
   set @sql1 = tmpSqlStr;
   prepare tmpSqlToRun from @sql1;
  
   select ( tmpSqlStr) into tmpExistDataCount;
  

   if tmpExistDataCount = 0  then
      set p_ColumnDatas =  REPLACE(p_ColumnDatas,tmpSplitData,",");
      set tmpSqlStr = " ";
      set tmpSqlStr = concat(tmpSqlStr ,"  insert into  " , p_TableName);
      set tmpSqlStr = concat(tmpSqlStr ," (  ", p_ColumnNames, " ) values ( "  ,p_ColumnDatas , " ) ;" );
      SET @sql = tmpSqlStr;
      prepare tmpSqlToRun from @sql;
     
    --  select tmpSqlStr;
     
      execute tmpSqlToRun;
  
   end if;

END;


--测试
CREATE TABLE `table1` (
  `field1` int(11) NOT NULL,
  `field2` varchar(20) DEFAULT NULL,
  `field3` datetime DEFAULT NULL,
  PRIMARY KEY (`field1`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;


call mysql_sp_insert_data("table1","field1,field2,field3","1@'1'@null");

原文地址:https://www.cnblogs.com/freeliver54/p/1851641.html