ch5 数据库系统概念(第6版)第五章高级sql.doc

数据库系统 上海交通大学计算机系 张忠能 zhang-zn@ 1 第5章:高级SQL 第5章:高级SQL SQL数据类型和模式 函数和过程结构 触发器 高级聚集功能 OLAP 用编程语言接入SQL* ?动态SQL ?JDBC 和 ODBC ?嵌入式SQL 过程扩展和存储过程 SQL 提供模块语言 ?SQL允许用if-then-else语句,for和while循环,等等 ,来定义过程. 存储过程 ?可以在数据库中存储过程 ?然后通过call语句来执行 ?允许外部应用程序对数据库进行操作,而无需了解内 部细节 面向对象方面将在22章介绍 (基于对象的数据库)* 函数和过程 SQL:1999 支持函数和过程 ?函数/过程可以用SQL语言书写,也可以使用其他外部 程序语言. ?函数对于特殊新的数据类型,例如图片和几何对象特 别有用. ?例如: 用于检查多边形是否重叠,或者比较图片相 似性的函数. ?一些数据库系统支持表值函数, 返回一个关系作为结果. SQL:1999 还支持大量的命令式结构,例如 ?循环, if-then-else, 赋值 许多数据库对不同于SQL:1999的SQL提供专有的 过程扩展. SQL函数 定义一个函数, 输入部门名字, 返回该部门的教师数 量. create function dept_count (dept_name varchar(20)) returns integer begin declare d_count integer; select count (* ) into d_count from instructor where instructor.dept_name = dept_name return d_count; end 用法:列出拥有超过12名教师的部门名字以及预算. select dept_name, budget from department where dept_count (dept_name ) 12 表函数 SQL:2003 增加了能够返回一个关系的函数 例如: 返回给定顾客所拥有的所有账户 create function instructors_of (dept_name char(20) returns table ( ID varchar(5), name varchar(20), dept_name varchar(20), salary numeric(8,2)) return table (select ID, name, dept_name, salary from instructor where instructor.dept_name = instructors_of.dept_name) 用法 select * from table (instructors_of (‘Music’)) SQL过程 dept_count 函数可以被写成如下过程: create procedure dept_count_proc (in dept_name varchar(20), out d_count integer) begin select count(*) into d_count from instructor where instructor.dept_name = dept_count_proc.dept_name end 可以使用 call语句从SQL过程中或者从嵌入式SQL中调用 过程. declare d_count integer; call dept_count_proc( ‘Physics’, d_count); 过程和函数也可以从动态SQL中调用 SQL:1999 允许超过一个函数/过程拥有相同的名字 (称作 名字超载), 只要参数的数量是不同的, 或者至少参数的类 型是不同的. 过程结构* 注意: 大部分数据库系统对下列标准语法实现了自 己的变种 ?阅读系统手册,查看相关的系统语法 复合语句: begin … end, ?在begin和end之间可能包含多个SQL语句. ?局部变量可以在一个复合语句中被声明 While 和 repeat 语句: declare n integer default 0; while n 10 do set n = n + 1 end while repeat set n = n – 1 until n = 0 end repeat 过程结构应用 存储过程 创建存储过程,存储过程是保存起来的可以接受和返回 用户提供的参数的 Transact-SQL 语句的集合。 可以创建一个过程供永久使用,或在一个会话中临时使 用(局部临时过程),或在所有会话中临时使用(全局 临时过程)。

文档评论(0)

1亿VIP精品文档

相关文档