博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql 存储过程动态执行sql语句
阅读量:6679 次
发布时间:2019-06-25

本文共 1783 字,大约阅读时间需要 5 分钟。

 之前经常在程序中拼接sql语句,其实我们也可以在存储过程中拼接sql 语句,动态的执行~~

 代码如下:

 

DROP PROCEDURE IF EXISTS SearchByDoctor;

CREATE PROCEDURE SearchByDoctor(
IN DoctorId VARCHAR(50),
IN deptId VARCHAR(50),
IN beginDate VARCHAR(20),
IN endDate VARCHAR(20),
IN StandDeptId VARCHAR(50),
IN OperationFlag VARCHAR(50),
IN SsczflId VARCHAR(50),
OUT OperNum INT,
OUT AvgDangerIndex DOUBLE,
OUT OperGrCase INT
)
BEGIN
DECLARE cal1 VARCHAR(800);
DECLARE cal2 VARCHAR(800);

SET cal1="SELECT COUNT(1),AVG(DANGER_INDEX) INTO @para1,@para2 FROM yw_ssxxb WHERE 1=1 ";
SET cal2="SELECT COUNT(1) INTO @para3 FROM gr_grbw WHERE OPE_RELID IN (SELECT RELID FROM yw_ssxxb WHERE 1=1";

#拼接医生id

SET cal1=CONCAT(cal1," ","AND OPEDOC_ID = ","'",DoctorId,"'");
SET cal2=CONCAT(cal2," ","AND OPEDOC_ID = ","'",DoctorId,"'");
#拼接科室id
IF deptId <>'' THEN
SET cal1=CONCAT(cal1,"AND DEPT_ID =","'",deptId,"'");
END IF;

#拼接开始结束日期

IF beginDate<>'' AND endDate <>'' THEN
SET cal1=CONCAT(cal1," ","AND OPER_AT BETWEEN ","'",beginDate,"'"," AND ","'",endDate,"'");
END IF;
#拼接标准科室
IF StandDeptId<>'' THEN
SET cal1=CONCAT(cal1," ","AND DEPT_ID IN ( SELECT ID FROM department WHERE STAND_DEPT_ID = ","'",StandDeptId,"'",")");
END IF;

#拼接数据来源

IF OperationFlag <>'' THEN
SET cal1=CONCAT(cal1," ","AND OPEPARTKINDID IN (SELECT ID FROM zh_ssczfl WHERE FLAG= ","'",OperationFlag,"'",")");
END IF;

#拼接手术操作类别

IF SsczflId <> '' THEN
SET cal1=CONCAT(cal1," ","AND OPEPARTKINDID = ","'",SsczflId,"'");
END IF;

SET cal2 =CONCAT(cal2,")");

SET @sql1=cal1;

SET @sql2=cal2;

PREPARE stmt1 FROM @sql1;

EXECUTE stmt1;
DEALLOCATE PREPARE stmt1 ;

PREPARE stmt2 FROM @sql2;

EXECUTE stmt2;
DEALLOCATE PREPARE stmt2 ;

SET OperNum=@para1;

SET AvgDangerIndex=@para2;
SET OperGrCase=@para3;

END;

 

 涉及到的具体的业务逻辑就不介绍了,语法方面还是可以参照下的。

转载于:https://www.cnblogs.com/drcoding/p/4270241.html

你可能感兴趣的文章
apache服务器显示md文件
查看>>
新一周冲刺计划3
查看>>
新一周冲刺5
查看>>
LeetCode 131. Palindrome Partitioning 20170706
查看>>
我的JavaScript学习笔记
查看>>
Microsoft Client Development MVP 2013 - 2014
查看>>
Jquery blokckUI 快速入门
查看>>
LeetCode 527 Word Abbreviation
查看>>
20160728
查看>>
NOI十连测 第四测 T3
查看>>
Codeforces 414B Mashmokh and ACM
查看>>
阿卡分糖果
查看>>
《软件工程-理论、方法与实践》读书笔记二
查看>>
将字符串str1复制为字符串str2的三种方法
查看>>
Vue项目经验
查看>>
八皇后问题,递归法实现
查看>>
Sharc FLAGS I/O Register(flag0~3)
查看>>
图片等比例缩放
查看>>
Python之异常
查看>>
Stringbuilder & Stringbuffer
查看>>