delimiter $$
CREATE PROCEDURE getDeviceRow7
(
IN deviceType VARCHAR(50),
IN page INT(10),
IN size INT(10) ,
IN deviceValue VARCHAR(50)
)
BEGIN
-- 1.定义一个sql变量
SET @sql = NULL;
-- 2.把我们的查询设备的sql赋给变量
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(IF(DEVICE_NAME_EN = ''', DEVICE_NAME_EN, ''', DEVICE_VALUE, NULL)) AS ', DEVICE_NAME_EN ) ) INTO @sql
FROM t_dap_device ;
-- 2.1拼接上条件的sql
set @whereSql = if((deviceType is null) or (deviceType=''),'',CONCAT('AND DEVICE_TYPE= ',deviceType) ) ;
-- 2.21 拼接模糊条件
set @param =CONCAT('AND DEVICE_VALUE like '%',deviceValue,'%'');
-- 2.2 拼接上and 条件
set @andSql =if( (deviceValue is null) or (deviceValue='') ,'',CONCAT( ' and DEVICE_NAME_EN = ''deviceName''', @param ) );
-- 2.3拼接分页sql
set @page =CONCAT(' LIMIT ', page ,',', size);
-- 2.4 拼接group by
set @g =' GROUP BY DEVICE_ID ';
-- 3.拼接sql
SET @sql = CONCAT('SELECT DEVICE_ID, DEVICE_NAME_EN, ', @sql ,'
FROM t_dap_device where 1=1 ',@whereSql,'',@andSql,'',@g,'',@page );
-- 预处理语句
PREPARE stmt FROM @sql;
-- 执行
EXECUTE stmt;
-- 销毁
DEALLOCATE PREPARE stmt;
END$$
delimiter;
-- 删除一个存储过程
DROP PROCEDURE getDeviceRow7
-- 执行存储过程
CALL getDeviceRow7('',0,2,'');
参考博客
https://www.jb51.net/article/251890.htm
https://blog.csdn.net/MGmuscler/article/details/125149998
行转列的数据转化定义的存储过程(但是因为模糊查询的需求问题,不能的到很好的解决只能变换方案,这只是一个简单的案例初级入门的简单案例方便日后记忆)
标签:存储,set,--,转列,EN,记忆,sql,DEVICE,CONCAT From: https://www.cnblogs.com/al88cn/p/16720684.html