儲存過程
【Create是建立儲存過程,alter是更改、改變儲存過程】
【在第一次寫入儲存程序時用create,若修改預存程序程式之後,則alter取代create再執行】
【在資料庫中begin end為大括號的意思】
·建立預存程序的格式:
--(procedure可簡寫為proc)proc為程式、步驟的意思。後面接著預存程序名稱
create proc 儲存程序名稱
as
程式碼區塊
Go
--exec為執行的意思。執行預存程序
Exec 預存程序名稱
---------修改預存程序
alter proc hehe ---alter更改、改變的意思
as
select 學生學號,語文分數from fenshugo
exec hehe
-------------查詢多個表
create proc chaxunasbeginselect * f起* from xueshengendgoexec chaxun--------------帶參數的預存程序
create procucunguocheng @yican 意義為形參@ercan varchar(20)
asbegin print @yican+@ercan-------輸入學號,判斷學生優良、結業、不結業(三門課及格為優秀,兩門課及格為結業)alter proc biye@xuehao int --建立輸入變數asbegindeclare @y intdeclare @s intdeclare @w int
🎼語文分數>=60
select @s=COUNT(*) from fenshu where 學生學號=@xuehao and 數學分數>=60
select @w=COUNT(*) from fenshu where學生學號=@xuehao andw=COUNT(*) from fenshu where學生學號=@xuehao andw=COUNT(*) from fenshu where學生學號=@xuehao andw=COUNT(*) from fenshu where學生學號=@xuehao andw=COUNT(*) from fenshu where學生學號=@xuehao andw=COUNT(*) from fenshu where學生學號=@xuehao andw=COUNT(*) from fenshu where學生學號=@xuehao andw=COUNT(*) from fenshu where學生學號=@xuehao 和英文分數>=60
set @zongshu=@y+@s+@w
if @zongshu=3
print '優'
if @zongshu =2
🜠 print print'不結業'if @zongshu=0 print'輸入錯誤'endgo--------綜合練習題
(儲存過程綜合訓練)
建立一個貨物表:編號,貨物名稱,單位,價格,庫存數量,備註。 (10條資料)
之後,進貨,如果已有此貨,增加數量,否則,新增入資料庫表中。
出貨,如果有人要貨,判斷數量是否充足,充足減庫存,否則告知不足。
根據名字隨時刪除資料庫中的數據,有則刪除,無則告知。
------------建立資料庫及資料表,並插入資料----------
create database 筆記本
go
create table bijiben
(
declare @ybjbn nvarchar(20),@ykc int --@ykc為資料中的原有的庫存數
select @ybjbn=countben(名稱) from bijibenin -當資料庫中沒有輸入的資料時
begin
insert into bijiben values(@bianhao,@bjbn,@beizhu,@ji '
end
else if @ybjbn=1 --當資料庫中有輸入的資料時
set @ykc=@ykc+@jinhuo
update bijiben set 庫存=@ykc where 名稱=@bjbn print'此電腦已成功新增! ' endendgoexec jinhuo 11,'戴爾','dell',4200,10,'美國'----------------- -----出貨------------------------create proc chuhuo --建立出貨預存程序@name nvarchar(20 ), --要出貨的筆記型電腦名稱@shuliang int --出貨的數量asbegin declare @ygeshu
begin
declare @ygeshu
begin declare @ygeshu後剩餘的庫存 select @ygeshu=庫存from bijiben where 名稱=@name if @shuliang>@ygeshu --當出貨的數量大於庫存的數量時化🜋~
else begin set @hgeshu=@ygeshu-@shuliang set @hgeshu=@ygeshu-@shuliang )print'交易成功! '
end
end
go
exec chuhuo '蘋果',11
---------------------------刪除一款筆記本資料-------
create proc qingchu
@scbjbn nvarchar(20) --要刪除的筆記本的名稱
as
begin
數
select @sgeshu=COUNT(*) from bijiben where 名稱=@scbjbn
if @sgeshu=1
print'該筆記本的資料刪除成功! ' end if @sgeshu=0 print'未找到該名稱的筆記本~'end