MySQL创建存储过程

Navicat for MySQL创建存储过程及MyBatis调用存储过程


问题描述

一条语句实现向两个表中添加数据

前段时间遇到需求,向一个表中添加数据,获取新增主键值。再向另一个表添加数据,其中一个字段为前一个表的主键值。并返回第二次添加的表的自增主键值。上网查到的一个方法为使用存储过程,便按照这个思路试着实现一下,现将过程回忆记录下来。

项目环境

SSM框架项目+Navicat管理MySQL数据库

解决问题

一、Navicat for MySQL创建存储过程

1.新建函数→选择“过程”
在这里插入图片描述
2.添加参数

模式:
IN:输入参数
OUT:输出参数
INOUT:既作为输入参数,也作为输出参数

在这里插入图片描述
3.写存储过程里面要执行的内容

CREATE DEFINER=`root`@`%` PROCEDURE `InsertNewConsultation`(IN `user_id` int,IN `doc_id` int,IN `now_time` datetime,IN `disease_id` int,IN `patient_id` int,IN `patient_speak_text` text,OUT `patient_speak_id` int)
BEGIN
--声明变量
DECLARE consultation_id INT;
	insert into 
	consultation_basic
		(user_id,last_reply_text,last_reply_time,consultation_status,doctor_unread_number,disease_id,patient_unread_number,patient_id,doc_id)
	values
		(user_id,patient_speak_text,now_time,1,1,disease_id,0,patient_id,doc_id);
	
	SET consultation_id = @@identity;
	
	insert into 
	patient_speak
		(patient_speak_text,patient_user_id,patient_speak_time,isread,consultation_id)
	values
		(patient_speak_text,user_id,now_time,0,consultation_id);
	
	SET patient_speak_id = @@identity;

END

4.保存即可

二、MyBatis调用存储过程

<select id="insertConsultationBasic"  parameterType="com.xxx.platform.entity.NewConsultationCustom" 
 	resultType="com.xxx.platform.entity.NewConsultationCustom" statementType="CALLABLE">
	{
		CALL InsertNewConsultation(
			#{user_id,jdbcType=INTEGER,mode=IN},
			#{doc_id,jdbcType=INTEGER,mode=IN},
			#{last_reply_time,jdbcType=TIMESTAMP,mode=IN},
			#{disease_type_id,jdbcType=INTEGER,mode=IN},
			#{patient_id,jdbcType=INTEGER,mode=IN},
			#{patient_speak_text,jdbcType=VARCHAR,mode=IN},
			#{patient_speak_id,jdbcType=INTEGER,mode=OUT}
		)
	}
</select>

注:调用存储过程时,注意参数顺序不能错。

  • 14
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值