业务情景:根据年龄、性别、地区(省、市)至少一个条件查询用户。
创建用户表:
drop database if exists user;
create database user;
use user;
drop table if exists user_info;
create table user_info(
user_name varchar(16) not null,
sex int default 0,-- 0指男性 1指女性
age int default null,
introduction varchar(10000) default null, -- 个人简介
province varchar(100) default null,
city varchar(100) default null
);
插入测试数据:
insert into user_info values
('xiaoming','0','18',null,'广东','深圳'),
('lee','1','22',null,'浙江','杭州'),
('dear','1','16',null,'湖南','长沙'),
('student','0','16',null,'湖南','长沙'),
('teacher','0','22',null,'广东','广州')
创建存储过程:
drop procedure if exists select_user;
DELIMITER $$ -- 更改分隔符,否则编译器默认';'作为结束标志,存储过程编译会报错。
-- 将搜索条件作为参数传入
create procedure select_user(in age int,in sex int,in province varchar(200),in city varchar(200))
begin
-- 创建原始select语句,加入where 1=1方便后续拼接
set @s='select user_name,sex,age,introduction,province,city from user_info where 1=1';
-- 如果搜索条件不为null,使用concat()函数进行拼接
if(age is not null)
then set @s=concat(@s,' and age=',age);
end if;
if(sex is not null)
then set @s=concat(@s,' and sex=',sex);
end if;
if(province is not null&&province!='')
-- 注意对单引号的转义
then set @s=concat(@s,' and province=\'',province,'\'');
end if;
if(city is not null&&city!='')
then set @s=concat(@s,' and city=\'',city,'\'');
end if;
-- 拼接完成后可以调用 select @s 语句,查看最终拼接的sql语句是否正确
-- select @s;
prepare stmt from @s;-- 预编译一条sql语句,并命名为stmt
execute stmt;-- 执行预编译sql
end
$$
DELIMITER ;
测试存储过程
call select_user(null,null,null,null);
call select_user(null,16,null,null);
call select_user(null,18,'广东',null);