当前位置:网站首页>[Database and SQL study notes] 10. (T-SQL language) functions, stored procedures, triggers

[Database and SQL study notes] 10. (T-SQL language) functions, stored procedures, triggers

2022-08-05 05:38:00 takedachia

工具:SQL Server 2019 Express
操作系统:Windows 10


用到的数据库备份: teaching.bak

回顾一下表结构:

t_student (S#, Sname, Sex, Age, Major)
t_teacher (T#, Tname, Age, Title)
t_course (C#, Cname, T#)
t_student_course (S#, C#, Score)

函数(function)

函数是由一个或多个T-SQL语句组成的子程序,可用于封装代码以便重新使用.
T-SQLProvides a wealth of ready-made data manipulation functions(such as those that have been encountered beforegetdate()等),To complete various data management tasks.
We can also define functions ourselves.

Depending on the form of the return value,User-defined functions are divided into:

  1. 标量函数:Returns a scalar value of the determined type
  2. 内嵌表值函数:返回一张表
  3. 多语句表值函数:A combination of the above two

例1:

create function average(@cn char(7)) returns float
as
begin
	declare @aver float
	select @aver=(select avg(Score) from t_student_course
					where C#[email protected])
	return @aver
end

解释
创建标量函数average.定义了一个参数@cn,类型char(7).returnsAfter defining the return value type,类型为float.
asfollowed by a block of function statements.
Parameters are passed in the statement [email protected] course number as the course selection table,Calculate the average score for that course number,作为return的返回值.

We enter the above code in the query box after execution,This function will be viewed in the corresponding location in the Object Explorer:
在这里插入图片描述

调用函数
Note when calling custom scalar-valued functions,Owner must be specified.这里就叫 dbo.average .
在这里插入图片描述


例2:

create function st_func(@major char(10)) returns table
as
return
	(select t_student.S#, Sname, C#, Score
	from t_student, t_student_course
	where [email protected] and t_student.S#=t_student_course.S#)

解释
创建表值函数,returns指定为table.
asdirectly definedreturn的内容.
The function queries the specified professional name(@major)的学生的学号、姓名、课程号、成绩.

调用函数
Be careful when calling table-valued functions,No need to specify an owner:
在这里插入图片描述

存储过程(procedure)

Stored procedures are a class of database objects,It is stored independently in the database.
Stored procedures can accept input parameters、输出参数,返回单个或多个结果集以及返回值,Executed by the application by calling.

存储过程的特点:

  1. 模块化程序设计
  2. Faster execution
  3. 减少网络流量
  4. 保证数据库安全

Stored procedures can be divided into:
系统存储过程(存在master库中,以’sp_'开头命名)
本地存储过程(用户自行创建,Stored in the user database)
临时存储过程
远程存储过程(on a remote server,用于分布式查询)
扩展存储过程

系统存储过程

System stored procedures existmaster库中,以’sp_'开头命名.例子:
sp_help
在这里插入图片描述

本地存储过程(自定义存储过程)

例1:

create procedure student_avg
as
select S#, avg(Score) as 平均分
from t_student_course
group by S#

This is a parameterless stored procedure.
Stored procedure save location:
在这里插入图片描述

执行
在这里插入图片描述


例2:

create procedure GetStudent
	@number char(10)
as
select * from t_student
where S#[email protected]

创建有参存储过程.

执行
The parameters passed in the stored procedure directly follow the name of the stored procedure with a space after it.
在这里插入图片描述


例3:

create procedure Student_Name
	@name varchar(30) = '%'
as select * from t_student
where Sname like @name

设定默认参数,Set to wildcard.

执行
The incoming parameters also contain wildcards.
在这里插入图片描述


例4(With input and output parameters):

create procedure Student_avg2
	@number char(10), @avgscore int output
as
select @avgscore=avg(Score)
from t_student, t_student_course
where t_student.S#=t_student_course.S# and t_student.S#[email protected]

Stored procedure with input and output parameters,When defining parameters, specify asoutput,Then assign values ​​to the output parameters when defining the procedure.

执行
Call a stored procedure with input and output parameters,先定义一个变量.
The location to pass in the output parameter(指定output),to assign,最后用select打印.
在这里插入图片描述


例5: Grade the student's average grade

create procedure getgrade
	@sid char(9), @grade char(1) output
as
declare @avgs int
select @avgs=avg(Score) from t_student_course where S#[email protected]
if @avgs>90 set @grade='A'
else if @avgs>80 set @grade='B'
else if @avgs>60 set @grade='C'
else set @grade='D'

定义了一个中间变量@avgs,Then make a judgment.

也可以用case语句写:

create procedure getgrade2
	@sid char(9), @grade char(1) output
as
declare @avgs int
select @avgs=avg(Score) from t_student_course where S#[email protected]
set @grade = case
	when @avgs>90 then 'A'
	when @avgs>80 and @avgs<=90 then 'B'
	when @avgs>60 and @avgs<=80 then 'C'
	else 'D'
end

执行
获取学号为2021001grades of students:
在这里插入图片描述

触发器(trigger)

Triggers are also essentially a stored procedure,is one when the base table is modified自动执行inline process,Mainly triggered by events and executed.
(Personally I think it can be comparedpython的魔法方法)
Triggers are often used to ensure data integrity.

分类:

  1. DML触发器:
    occurs in the database serverINSERT、UPDATE、DELETE等事件(Data manipulation language events)时被触发.
    表层面.
  2. DDL触发器
    when executed in the database serverDDLFired when a data definition language occurs,如添加、When deleting or modifying the database.
    数据库层面.

We can define triggers,下面是例子.


DML触发器

例1:Define a modification trigger,打印提示:

create trigger reminder1
on t_student
for
update
as print 'You are modifying data in the student table'

The defined triggers can be found in the corresponding table in the Object Explorer:
在这里插入图片描述

执行效果
在这里插入图片描述


例2:Define the insert data trigger,Print the prompt and undo the action:

create trigger reminder2
on t_student
for
insert
as print 'You are adding data to the student table'
rollback

写上rollbackThe statement can perform a rollback,to undo the operation.

执行效果
在这里插入图片描述


例3:删除表中数据时,执行一个select操作:

create trigger print_table
on t_student
for
delete
as select * from t_student

效果略.

临时表

需要了解的是,SQL Server为每个DMLTriggers define two special temporary tables:inserted 和 deleted,stored in the database server's memory,为只读.
During trigger execution,The system will create and maintain these two temporary tables,triggerIt will be deleted after execution.
用户执行insert时,All added records are stored in inserted表中;
执行delete时,All deleted records are stored at deleted表中;
执行update时,Modified records are first stored in deleted,The modified data is then storedinserted中.

DDL触发器

例:Create a delete table in the current database、Trigger to change the table,Undo delete and modify operations:

create trigger limited
on database
for drop_table, alter_table
as print 'Table modification or deletion is not allowed'
rollback

效果略.

Call the stored procedure in the trigger

We can call stored procedures in triggers,直接在as后面写上 exec + 存储过程 即可.
例:

create proc p1 as
select * from t_student

create trigger tr1 on t_student
for insert, update, delete
as exec p1
原网站

版权声明
本文为[takedachia]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/217/202208050513158267.html