mysql编程 自定义函数 存储函数

来源:互联网 发布:php环境文件管理器 编辑:程序博客网 时间:2024/06/07 07:06
================================
= SQL编程       =
================================

【结束符】 \g \G

【变量】:1、系统变量 2、用户自定义变量
//  变量的有效范围是,从连接建立到断开。

★ 系统变量:查看系统变量( show variables)

★ 自定变量:set 变量名 = 变量值;
【注意】:用户定义变量前加 @ 符号
【例】:set @huge = '飞虎';
select @huge;

【定义变量 select into 】
【例】:-- 设置到变量中
select 10, 13, 14 into @a, @b, @c ;
-- 查看设置的变量
select @a, @b, @c ;
【注意】:select into @var 要求只能返回一行。

【select通过表达式给变量赋值】
【例】:select @who := '薛';
【注意】: :=是赋值符号,=是关系运算符;

【set】-- 专门为变量赋值的形式
【例】:set @who := '薛';
【例】:set @total := (select count(*) from table);
【注意】
★ 作用域。全局/局部。
★ 有效期。会话结束(连接断开)

=============================
= 函数       =
=============================

【函数分类】:1、内置函数
          2、自定义函数

【内置函数】:1、数值。rand()、format(a, b)、
          2、字符串。substring()、concat()、charat()、
length() 字节数 、char_length() 字符数 、
lpad('a', 3, 0) 占3位,补0
          3、日期时间。now()、unix_timestamp()、form_unixtime(1234)、
        4、聚合
         5、流程控制
          6、其他。md5()、password() mysql独有的、sha1()

【存储函数】
【语法】:create function 函数名 (参数列表) 返回值
函数体
【例】:delimiter $$
create function sayHello() returns varchar(20)
begin
return 'hello world!';
end
$$

delimiter ;
【注意】:函数是与当前数据库绑定的,但可以通过数据库名函数名调用。

【流程控制】:1、分支;2、循环。
★ 1、分支
if 条件1 then
执行语句
elseif 条件2 then
执行语句
...
else
执行语句

【例】:delimiter $$
create function func1() returns varchar(20)
begin
if hour(now()) >= 18 then
return '晚';
else
return '早';
end if;
end
$$

delimiter ;

★ 2、循环
【例】:delimiter $$
create function func2() returns int
begin
-- 1-10的和
set @i = 1;
set @sum = 0;
while @i <= 10 do
set @sum = @sum + @i;
set @i = @i + 1;
end while;
return @sum;
end
$$
delimiter ;
【注意】:循环提前终止条件。1、leave -- 跳出循环;
  2、iterate -- 跳出单次

【例】:delimiter $$
create function func3() returns int
begin
-- 1-10的和
set @sum = 0;
w:while @i < 10 do-- 设置开始标记 w
set @i = @i + 1;
if @i = 5 then
iterate w;
end if;
set @sum = @sum + @i;
end while w; -- 结束标记 w;
return @sum;
end
$$
delimiter ;

【函数内使用的变量】
★ @var形式 (全局变量),函数内外都可以使用。

★ 函数的参数 (局部变量)
【例】:delimiter $$
create function func4(username varchar(10)) returns varchar(20)-- 局部变量
begin
return concat('hello', username);
end
$$
delimiter ;

【例】:declare i int default 0;-- 声明局部变量

【例】:delimiter $$
create function sname() returns char(2)
begin
declare first_name char(16) default '赵钱孙李周吴郑王冯陈朱魏将神汉阳';
declare last_name char(10) default '甲乙丙丁午己庚辛壬葵';
declare full_name char(2);
set full_name = concat(substring(first_name, floor(rand()*16 + 1), 1), 
substring(last_name, floor(rand()*10 + 1), 1));
return full_name;
end
$$
delimiter ;
0 0
原创粉丝点击