mysql 判断是否已存在及插入表数据 的 简单存储过程
處理思路:
1、查找判斷 相同數(shù)據(jù)是否已存在
2、如不存在,則執(zhí)行Insert操作
CREATE PROCEDURE `mysql_sp_insert_data`(
? IN p_TableName varchar(100)?? --表名
, IN p_ColumnNames varchar(200) --字段組合 ,以","分隔
, IN p_ColumnDatas varchar(500) --數(shù)據(jù)組成 ,以"@"分隔
)
??? 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");
總結(jié)
以上是生活随笔為你收集整理的mysql 判断是否已存在及插入表数据 的 简单存储过程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GoogleClosureLibrary
- 下一篇: 人生致命的8个经典问题,你也常常犯傻