MySQL编程从入门到精通:流程控制、变量与存储过程详解
MySQL语句块基础
MySQL中的语句块使用begin...end结构,类似于JavaScript或PHP中的大括号{}语法:
Basic MySQL Statement Blocks
MySQL uses begin...end structure for statement blocks, similar to curly braces {} in JavaScript/PHP:
[标识符:] begin
//语句...
end [标识符];
流程控制语句
MySQL支持多种流程控制结构:
Flow Control Statements
MySQL supports multiple flow control structures:
1. IF语句
if (条件判断) then
begin
//代码...
end;
end if;
2. CASE语句
有两种语法形式:
CASE Statements
Has two syntax forms:
语法1:
case @v1
when 1 then begin...end;
when 2 then begin...end;
else begin...end;
end case;
语法2:
case
when @v1 > 0 then begin...end;
when @v1 < 0 then begin...end;
else begin...end;
end case;
循环结构
Loop Structures
1. LOOP循环
标识符: loop
begin
if (条件) then leave 标识符; end if;
end;
end loop 标识符;
2. WHILE循环
set @v1 = 1;
while @v1 < 10 do
begin
insert into tab1 values(null, @v1);
set @v1 = @v1 + 1;
end;
end while;
3. REPEAT循环
set @v1 = 1;
repeat
begin
insert into tab1 values(null, @v1);
set @v1 = @v1 + 1;
end;
until @v1 >= 10
end repeat;
MySQL变量类型
MySQL Variable Types
1. 普通变量
declare 变量名 类型 [default 值];
set 变量名 = 值;
2. 会话变量
set @变量名 = 值;
select @变量名 := 值;
select 值 into @变量名;
存储函数与存储过程
Stored Functions & Procedures
1. 存储函数
create function 函数名(参数) returns 类型
begin
//代码...
return 值;
end;
2. 存储过程
create procedure 过程名([in|out|inout] 参数名 类型)
begin
//代码...
end;
触发器
Triggers
create trigger 触发器名 before|after insert|update|delete
on 表名 for each row
begin
//可以使用new和old访问数据
end;
SEO优化提示:
本文包含MySQL编程核心概念,适合搜索"MySQL编程"、"存储过程"、"触发器"等关键词的用户。
SEO Optimization Tip:
This article covers core MySQL programming concepts, targeting keywords like "MySQL programming", "stored procedures", "triggers".
