企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**1. 语法** ```sql # 语法1 CASE case_value WHEN when_value THEN statement_list [WHEN when_value THEN statement_list] ... [ELSE statement_list] END CASE # 语法2 CASE WHEN condition THEN statement_list [WHEN condition THEN statement_list] ... [ELSE statement_list] END CASE - case_value:当 case_value = when_value 时,执行 statement_list 语句 - condition:条件成立则执行 statement_list 语句 ``` **2. 演示** ```sql # 1. 准备演示数据 drop table if exists account; create table account ( `id` int(11) primary key auto_increment not null, `username` varchar(255) not null, `password` varchar(255) not null ); insert into account values(1, '张三', 'zhangsan'); insert into account values(2, '李四', 'lisi'); # 2. 在存储过程中使用 case 语句 delimiter $ create procedure proce_account02(in id_ int, in uname varchar(255), in pass varchar(255)) begin case when id_ = 1 then update account set username=uname, password=pass; when id_ = 2 then delete from account where id=id_; else insert into account values(id_, uname, pass); end case; end $ # 3. 调用存储过程 call proce_account02(3, '王五', 'wangwu') $ # 4. 查看结果 mysql> select * from account $ +----+----------+----------+ | id | username | password | +----+----------+----------+ | 1 | 张三 | zhangsan | | 2 | 李四 | lisi | | 3 | 王五 | wangwu | +----+----------+----------+ ``` **3. 在 select 语句中使用 case 语句** ```sql select case when id = 1 then 'one' when id = 2 then 'two' when id = 3 then 'three' end as result, id, username from account; +--------+----+----------+ | result | id | username | +--------+----+----------+ | one | 1 | 张三 | | two | 2 | 李四 | | three | 3 | 王五 | +--------+----+----------+ ```