一、注释
# 单行注释
-- (两个横线一个空格) 单行注释
/* */ 多行注释
二、语句分隔符
默认的有以下三种
; \g \G
修改语句分隔符
delimiter DELIM; #除了 \,任何字符都可以作为语句分隔符
1. 定义变量
set var=valur 或者 set var:=value
select STATEMENT into var_list;
2. 获取变量值
select var;
3. 声明局部变量, 通常用在存储过程或函数中
declare COLUMN_DEFINITION;
# eg:
declare i int default 0;
1) 字段就是变量,为了区分系统变量、字段和自定义变量,通常在自定义变量名前加 @ 符号
2) select @who='lisi'; # 此处的 = 号是关系表达式
3) select @who:='lisi'; # := 是赋值表达式
四、流程控制语句
1. if
if CONDITION1 then
statement;
...
elseif CONDITION2 then
statement;
...
else
statement;
...
end if;
case var
when value1 then
statement;
...
when value2 then
statement;
...
else
statement;
...
end case;
case
when CONDITION1 then
statement;
...
when CONDITION2 then
statement;
...
else
statement;
...
end case;
SELECT CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END;
SELECT CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END;
while CONDITION do
statement;
...
end while;
repeat
statement;
...
until CONDITION end repeat;
leave 相对于 break
iterate 相对于 continue
五、MySQL函数
查看函数
show function status;
show create function FUNC_NAME;
drop function [if exists] FUNC_NAME;
delimiter $
create function FUNC_NAME(arg1, arg2, ...) returns ret_type
begin
# function body
statement;
...
end$
delimiter ;
select [db_name.]FUNC_NAME(arg1, arg2, ...);
drop function if exists sayHello;
delimiter $
create function sayHello(name varchar(10)) returns varchar(20)
begin
return concat('hello ',name);
end$
delimiter ;
六、MySQL存储过程
查看
show procedure status;
show create procedure PRO_NAME;
删除
drop procedure [if exists] PRO_NAME;
调用
call PRO_NAME();
创建
delimiter $
create procedure PRO_NAME(arg1, arg2, ...)
begin
# procedure body
statement;
....
end$
delimiter ;
delimiter $
create procedure p1(num int, flag char(1))
begin
if flag='h' then
select * from TABLE_NAME where id>num;
else
select * from TABLE_NAME where id
IN 类似于编程语言中的“函数传参”,默认
OUT 存储过程内部会修改此全局变量的值
INOUT IN/OUT 的结合
eg:
delimiter $
drop procedure if exists p$
create procedure p(IN num int, OUT total int)
begin
declare i int default 0;
set i := 1;
set total := 0;
while i<=num do
set total := total + i;
set i := i+1;
end while;
end$
delimiter ;
mysql> set total=0; # 需要事先定义 total 为全局变量
mysql> call p(10, total);
mysql> select total; # total 值被修改
delimiter $
drop procedure if exists p$
create procedure p(INOUT total int)
begin
set total := total + 20;
end$
delimiter ;
mysql> set total=10;
mysql> select total; # 10
mysql> call p(total);
mysql> select total; # 20
通过编译预处理把“表名”作为“参数”传递
drop procedure if exists p;
delimiter $$
create procedure p(t_name varchar(10))
begin
# 拼接 SQL 语句
set @sql=concat('select * from ',t_name);
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
end$$
delimiter ;