存儲過程:就像函數一樣的會保存在資料庫中--》可編程性 --》 存儲過程創建存儲過程:create proc JiaFa--需要的參數@a int,@b intas --存儲過程的內容 declare @c int; set @c = @a + @b; return @c;go public int ...
存儲過程:就像函數一樣的
會保存在資料庫中--》可編程性 --》 存儲過程
創建存儲過程:
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