dream

一个菜鸟程序员的成长历程

0%

数据库系统原理第十一节

数据库系统原理第十一节

数据库编程

存储过程体

使用 declare 声明局部变量

1
declare cid int(10) 0;
  • 只能值begin end中声明
  • 必须在存储过程开头声明
  • 不同于用户变量
  • 作用范围仅限于声明他的begin end语句块

局部变量和用户变量的区别

  • 局部变量前面没有@符号,并且他只能被声明的begin end语句块中使用
  • 用户变量在声明时前面有@符号,同时已声明的用户变量存在于整个会话之中

使用 set 为局部变量赋值

1
set cid = 910;

select id into cid table

流程控制语句

条件判断
if 条件 then
表达式1
else
表达式2
end if

循环语句

  • while
  • repeat
  • loop

iterate语句
用于表示退出当前循环

declare cursor创建游标

1
declare cursor_name cursor for select_statement

open 打开游标

1
open cursor_name

使用 fetch into 读取游标数据
读取已打开的游标

1
fetch cursor_name into var_name

使用 close 关闭游标

1
close cursor_name

存储函数

由SQL语句和过程式语句组成

使用 create function 创建

1
2
3
create function sp_name(参数)
returns type
routine_body //主体

给定id号返回性别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use test;
delimiter $$
create function fn_search(cid int)
returns char(20)
deterministic
begin
declare sex char(20)
select cust_sex into sex from customers where id = cid;
if sex is null then
return(select '没有该客户');
else
if sex = 'F' then
return(select '女');
else
return(select '男');
end if;
end if;
end $$

存储函数和存储过程的区别
存储函数不能有输出参数,存储过程有
存储函数必须包含一条return语句,存储过程不包含return
存储函数可以直接调用,不需要call,存储过程必须call

使用 select 调用存储函数

1
select fn_search(1)$$

删除存储函数

1
drop function fun_name

数据库安全和保护

数据库完整性

正确性和相容性

  • 列级约束,包含列的类型,取值范围,精度
  • 元组约束,指元组中各个字段之间的约束
  • 表级约束,指若干元组,关系之间的联系的约束

实体完整性:主键约束和候选键约束

主键

  • 一个表只能有一个主键
  • 主键唯一,不能为NULL
  • 复合主键不能包含不必要的多余列
  • 一个列名在复合主键的列表中只能出现一次

主键约束:primary key, create table 或 alter table,一个表只能创建一个主键
候选键约束:unique, create table 或 alter table,可以定义若干个候选键

参照完整性
1
2
3
4
5
references table_name(index_col_name)
[on delete reference_option]
[on update reference_option]

restrict|cascade|set null|no action