当前位置:网站首页>[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:
- 标量函数:Returns a scalar value of the determined type
- 内嵌表值函数:返回一张表
- 多语句表值函数: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.
存储过程的特点:
- 模块化程序设计
- Faster execution
- 减少网络流量
- 保证数据库安全
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.
分类:
- DML触发器:
occurs in the database serverINSERT、UPDATE、DELETE等事件(Data manipulation language events)时被触发.
表层面. - 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
边栏推荐
猜你喜欢
【数据库和SQL学习笔记】5.SELECT查询3:多表查询、连接查询
MSRA提出学习实例和分布式视觉表示的极端掩蔽模型ExtreMA
6k+ star,面向小白的深度学习代码库!一行代码实现所有Attention机制!
【数据库和SQL学习笔记】8.SQL中的视图(view)
Flink 状态与容错 ( state 和 Fault Tolerance)
CAP+BASE
flink项目开发-flink的scala shell命令行交互模式开发
el-table,el-table-column,selection,获取多选选中的数据
spingboot 容器项目完成CICD部署
The fourth back propagation back propagation
随机推荐
用GAN的方法来进行图片匹配!休斯顿大学提出用于文本图像匹配的对抗表示学习,消除模态差异!
flink项目开发-flink的scala shell命令行交互模式开发
怎么更改el-table-column的边框线
el-pagination左右箭头替换成文字上一页和下一页
大型Web网站高并发架构方案
[After a 12] No record for a whole week
Service
解决端口占用问题
ECCV2022 | RU & Google propose zero-shot object detection with CLIP!
CVPR最佳论文得主清华黄高团队提出首篇动态网络综述
el-pagination分页分页设置
记我的第一篇CCF-A会议论文|在经历六次被拒之后,我的论文终于中啦,耶!
[Remember 1] June 29, 2022 Brother and brother double pain
day12函数进阶作业
flink实例开发-batch批处理实例
全尺度表示的上下文非局部对齐
11%的参数就能优于Swin,微软提出快速预训练蒸馏方法TinyViT
机器学习(一) —— 机器学习基础
Flink Table API 和 SQL之概述
Flink Broadcast 广播变量