SQL 存储和触发器

时间:2021-12-30 12:58:58

存储过程:就像函数一样的
会保存在数据库中--》可编程性 --》 存储过程

创建存储过程:
create proc JiaFa
--需要的参数
@a int,
@b int
as
--存储过程的内容
declare @c int;
set @c = @a + @b;
return @c;
go

public int JiaFa(int a, int b)
{
int c = a+b;
return c;
}
--执行完毕后全部选中,执行创建

执行存储过程:
exec JiaFa 3,5;

declare @f int;
exec @f = JiaFa 3,5;
print @f;

例:

--根据用户传入的参数查询汽车表符合该条件的汽车数量
create proc ChaXun
@n varchar(20)
as
declare @num int
select @num = count(*) from car where name like '%'+@n+'%'
return @num
go

declare @m int
exec @m = ChaXun '奥迪'
print @m

触发器:
是一个特殊的存储过程;
通过增删改的动作来触发执行,没有参数,没有返回值;

create trigger Insert_Student --命名规范
on student --针对于哪一个表
for insert --针对于哪一个动作来触发

-- onclick = "show()"

as
触发执行的代码段
go

----------------------------------------------------
create trigger Delete_Info
on info
instead of delete
as
declare @c varchar(20)
select @c = code from deleted

delete from work where infocode=@c
delete from family where infocode=@c
delete from info where code=@c
go

create trigger Delete_Nation
on nation
for delete
as

go

1.for的意思是在动作执行之后触发
2.instead of delete 的意思是删除之前引发,可以理解为替代,写了这个之后,写的执行代码就没有用了,就被触发器的代码覆盖了

触发器常用的为级联删除:
create trigger delete_student
on student
instead of delete
as
--如果要删除student表数据,那么需要级联删除
declare @sno varchar(20);
set @sno = sno from deleted --deleted固定格式,为删除执行所能删除的数据,并没有执行删除,而是把他们显示出来,在这获得要删除的数据的sno,然后先删除其他表中此sno的数据
delete from score where sno = @sno;
delete from student where sno = @sno;
go