Mysql存储过程Merge into(带入参)
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
MYSQL存储过程实现MERGE INTO函数;ORACLE、DM数据库自带此函数。
提示:以下是本篇文章正文内容,下面案例可供参考
一、Navicat版本信息
二、使用步骤
1.代码展示
代码如下(示例):
CREATE DEFINER=`root`@`localhost` PROCEDURE `MERGE_A_INTO_B`( IN `TYPEPARAM` VARCHAR(5), IN `STARTTIME` VARCHAR(20), IN `ENDTIME` VARCHAR(20))
BEGIN
DECLARE
_id VARCHAR ( 50 );
DECLARE
_tg_id DECIMAL ( 22 );
DECLARE
_tg_name VARCHAR ( 800 );
DECLARE
_tag_code DECIMAL ( 20 );
DECLARE
_insert_date DATE;
DECLARE
_remark VARCHAR ( 800 );
DECLARE
_state VARCHAR ( 20 );
DECLARE
DONE INT DEFAULT FALSE;
DECLARE
CUR_ACCOUNT CURSOR FOR SELECT DISTINCT
id,
tg_id,
tg_name,
tag_code,
insert_date,
remark,
state
FROM
D5000.XXXXX(源数据表)
WHERE
type = TYPEPARAM;
DECLARE
CONTINUE HANDLER FOR NOT FOUND
SET DONE = TRUE;
OPEN CUR_ACCOUNT;
READ_LOOP:
LOOP
FETCH NEXT
FROM
CUR_ACCOUNT INTO _id,
_tg_id,
_tg_name,
_tag_code,
_insert_date,
_remark,
_state;
IF
DONE THEN
LEAVE READ_LOOP;
END IF;
IF NOT EXISTS (
SELECT 1
FROM D5000.XXXXX(要匹配数据表) d
WHERE d.tg_id = _tg_id AND d.tag_code = _tag_code AND d.insert_date
BETWEEN DATE_FORMAT( STARTTIME, '%Y-%m-%d %H:%i:%s' ) AND DATE_FORMAT( ENDTIME, '%Y-%m-%d %H:%i:%s' )
)
THEN
INSERT INTO D5000.XXXXX(要匹配数据表) ( id, tg_id, tg_name, tag_code, insert_date, remark, state )
VALUES ( _id, _tg_id, _tg_name, _tag_code, _insert_date, _remark, _state ) ;
ELSE
UPDATE D5000.XXXXX(要匹配数据表) d SET d.update_date = _insert_date,d.remark = _remark,d.state = _state where d.tag_code=_tag_code and d.tg_id = _tg_id and d.insert_date
BETWEEN DATE_FORMAT( STARTTIME, '%Y-%m-%d %H:%i:%s' ) AND DATE_FORMAT( ENDTIME, '%Y-%m-%d %H:%i:%s' );
END IF;
END LOOP;
CLOSE CUR_ACCOUNT;
END
2.使用步骤
操作如下:
1.右键>新建函数
2.选择函数
3.输入函数名称>点击完成
4.Ctrl+a:全选删除 >Ctrl+v:将代码粘贴>Ctrl+s 保存即可;至此函数创建完成;
5.函数运行
# 温馨提示 记得修改表名