MySQL中拼接SQL语句

业务情景:根据年龄、性别、地区(省、市)至少一个条件查询用户。


创建用户表:

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);

这里写图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值