SQL Server存儲過程和觸發器的使用

存儲過程

(1)創建存儲過程,使用Employees表中的員工人數來初始化一個局部變量,并調用這個存儲過程。

1.	Create PROCEDURE test @number1 int output --輸出參數,可以從程序中返回信息  
2.	As  
3.	begin  
4.	    Declare @number2 int  
5.	    Set @number2=(Select COUNT(*) from Employees)  
6.	    Set @number1=@number2  
7.	end

運行結果如下

執行該存儲過程,并查看結果。

Declare?@num?int??
EXEC?test?@num?output??
Select?@num??

運行結果如下

(2)創建存儲過程,比較兩個員工的實際收入,若前者比后者高就輸出0,否則輸出1。

1.	Create PROCEDURE compa @id1 char(6),@id2 char(6),@bj int output  
2.	as  
3.	Begin  
4.	    Declare @sr1 float, @sr2 float  
5.	    Select @sr1=income-outcome from salary Where EmployeeID=@id1  
6.	    Select @sr2=income-outcome from salary Where EmployeeID=@id2  
7.	    If @sr1>@sr2  
8.	        Set @bj=0  
9.	    Else  
10.	        Set @bj=1  
11.	end  
12.	GO 

運行結果如下

(3)創建添加職員記錄的存儲過程EmployeeAdd。

Create?PROCEDURE?EmployeeAdd???
(??
@employeeid?char(6),@name?char(10),@education?char(4),?@birthday?datetime,??
@workyear?tinyint,@sex?bit,@address?char(40),?@phonenumber?char(12),??
@departmentID?char(3))??
As??
Begin??
Insert?into?employees???
values(@employeeid,@name,@education,@birthday,@workyear,??
@sex,@address,@phonenumber,@departmentID)??
end??
return

運行結果如下

(4)創建帶output游標參數的存儲過程,在employees中聲明并打開一個游標。

Create?PROCEDURE?em_cursor?@em_cursor?cursor?VARYING?output??
As??
Begin??Set?@em_curcor=CURSOR?forward_only?static??FOR??Select?*?from?Employees??open?@em_cursor??
end??

運行結果如下

聲明一個局部游標變量,執行上述存儲過程,并將游標賦值給局部游標變量,然后通過該游標變量讀取記錄

Declare?@mycursor?cursor??
EXEC?em_cursor?@em_cursor=@mycursor?output??
Fetch?next?from?@mycursor??
While(@@FETCH_STATUS=0)??
begin??fetch?next?from?@mycursor??
end??
close?@mycursor??
deallocate?@mycursor?

運行結果如下

(5)創建存儲過程,使用游標確定一個員工的實際收入是否排在前三名。結果為1表示是,結果為0表示否。

Create?PROCEDURE?top_three?@em_id?char(6),@ok?bit?output??
As??
Begin??Declare?@x_em_id?char(6)??Declare?@act_in?int,@seq?int??Declare?salary_ids?cursor?for??Select?EmployeeID,Income-Outcome?from?salary??order?by?income-outcome?desc??Set?@seq=0??Set?@ok=0??open?salary_ids??fetch?salary_ids?into?@x_em_id,@act_in??While?@seq<3?and?@ok=0??begin??Set?@seq=@seq+1??if?@x_em_id=@em_id??Set?@ok=1??fetch?salary_ids?into?@x_em_id,@act_in??end??close?salary_ids??deallocate?salary_ids??
end?

運行結果如下

執行該存儲過程

Declare?@ok?bit??
EXEC?top_three?'108991',@ok?output??
Select?@ok?

運行結果如下

要求一個員工的工作年份大于6時將其轉移到經理辦公室工作

1.	Select * from dbo.Departments  
2.	Select * from dbo.Employees  
3.	Select * from dbo.Salary   
4.	  
5.	Create PROCEDURE que1 @id char(6)  
6.	as  
7.	Begin  
8.	    Declare @workyear char(6),@dep_id char(3)  
9.	    Select @workyear=workyear from Employees Where EmployeeID=@id  
10.	    Select @dep_id=Departments.departmentID from employees,departments  
11.	        Where employees.DepartmentID=departments.DepartmentID   
12.	        and departmentName='經理辦公室'   
13.	    If @workyear>6  
14.	        Update Employees Set departmentID=@dep_id Where EmployeeID=@id  
15.	end 

根據每個員工的學歷將收入提高500

1.	Create Procedure que2 @id char(6)  
2.	As  
3.	Begin  
4.	    Declare @education char(6)  
5.	    Select @education=Education from Employees Where EmployeeID=@id  
6.	    Update salary Set Income=income+500 Where EmployeeID=@id  
7.	end 

使用游標計算本科及以上學歷的員工在員工總數中占的比例

1.	Declare @edu varchar(10),@part_count int,@all_count int  
2.	Declare mycursor cursor   
3.	for Select distinct education,count(education) over(partition by education)as part_count,  
4.	count(education) over() as all_count from Employees  
5.	open mycursor  
6.	fetch next from mycursor into @edu,@part_count,@all_count  
7.	While @@FETCH_STATUS=0  
8.	Begin  
9.	    print @edu+'占總人數比例:'+convert(varchar(100),convert(numeric(38,2),@part_count/1.0/@all_count*100)+'%'  
10.	    fetch next from mycursor into @edu,@part_count,@all_count  
11.	end  
12.	close mycursor  
13.	deallocate mycorsor  

觸發器

對于TGGL數據庫,Employees表的DepartmentID列與Departments表的DepartmentID列應滿足參照完整性規則。

  1. 向Employees表添加記錄時,該記錄的DepartmentID字段值在Departments表中應存在。
  2. 修改Departments表的DepartmentID字段值時,該字段在Employees表中的對應值也應修改。
  3. 刪除Departments表的記錄時,該記錄的DepartmentID字段值在Employees表中對應的記錄也應刪除。

對于上述參照完整性規則,在此通過觸發器實現。

(1)向Employees表插入一個記錄時,通過觸發器檢查記錄的DepartmentID在Departments中是否存在,不存在則取消插入或修改操作。

1.	Create Trigger employeesIns on dbo.Employees  
2.	    for insert,Update  
3.	    as  
4.	    Begin  
5.	        IF((Select DepartmentID from inserted)not in  
6.	            (Select DepartmentID from Departments))  
7.	            Rollback    
8.	    end 

運行結果如下

(3)刪除Departments中記錄的同時刪除Employees中DepartmentID對應記錄.

Create?Trigger?DepartmentDelete?on?dbo.Departments??for?Delete??as??Begin??Delete?from?Employees??Where?DepartmentID=(Select?DepartmentID?from?deleted)??end?

運行結果如下

(4)創建Instead of觸發器,當向salary中插入記錄時,先檢查EmployeeID列上的值在Employees中是否存在,如果存在則執行插入操作,如果不存在則提示“員工編號不存在”。

1.	Create Trigger EM_EXISTS on salary  
2.	Instead of Insert  
3.	as  
4.	Begin  
5.	    Declare @employeeID char(6)  
6.	    Select @employeeID=EmployeeID from inserted  
7.	    If (@employeeID in (Select EmployeeID from Employees))  
8.	        Insert into salary Select * from inserted  
9.	    Else  
10.	        print '員工編號不存在'  
11.	end

運行結果如下

(5)創建DDL觸發器,當刪除數據庫的一個表時,提示‘不能刪除表’,并回滾刪除表的操作。

Create?Trigger?table_delete?on?Database??
After?drop_table??
as??print?'不能刪除表'??rollback?transaction?

運行結果如下

Employees與salary的EmployeeID應滿足完整性規則,請用觸發器實現兩個表之間的參照完整性。

1.	Create Trigger que1_1 on salary  
2.	for insert,update  
3.	as  
4.	Begin  
5.	    If(Select employeeid from inserted)not in  
6.	    (Select EmployeeID from Employees)  
7.	    rollback  
8.	end  
9.	Create trigger que1_2 on Employees  
10.	for update  
11.	as  
12.	Begin  
13.	    Update Salary Set zemployeeID=(Select Employeeid from inserted)  
14.	    Where EmployeeID=(Select employeeid from deleted)  
15.	end  
16.	  
17.	Create Trigger que1_3 on Employees  
18.	for delete  
19.	as  
20.	Begin  
21.	    Delete from salary  
22.	    Where EmployeeID=(Select EmployeeID from deleted)  
23.	End

若將Employees中員工的工作時間增加到1年,則收入增加500,若增加兩年則增加1000。

1.	Create Trigger que2_1 on Employees  
2.	After update  
3.	as  
4.	Begin  
5.	    Declare @a int,@b int  
6.	    Set @a=(Select workyear from inserted)  
7.	    Set @b=(Select workyear from deleted)  
8.	    If (@a>@b)  
9.	        update salary  
10.	        Set income=income+(@a-@b)*500  
11.	        Where EmployeeID in (Select EmployeeID from inserted)  
12.	End 

創建UPdate觸發器,當salary中income增加500時,outcome增加50。

1.	Create Trigger que3_1 on salary  
2.	for update  
3.	as  
4.	Begin  
5.	    If((Select income from inserted)-(Select income from deleted)=500)  
6.	        Update salary Set outcome=outcome+50  
7.	        Where EmployeeID=(Select EmployeeId from inserted)  
8.	end 

創建instead of觸發器,實現向不可更新視圖插入數據。

1.	Create VIEW a_view  
2.	as  
3.	Select a.EmployeeID,name,workyear,income,outcome from Employees a,salary b  
4.	Where Employees.employeeID=Salary.EmployeeID  
5.	Create Trigger que4_1 on a_view  
6.	Instead of insert  
7.	as  
8.	Begin  
9.	    Declare @ei char(6),@name char(10),@wy tinyint,@ic float,@oc float  
10.	    Select @ei=EmployeeID,@name=name,@wy=workyear,@ic=income,@oc=outcome  
11.	    from inserted  
12.	    insert into Employees(EmployeeID,name,workyear)values(@ei,@name,@wy)  
13.	    insert into salary values(@ei,@ic,@oc)  
14.	end  

創建DDl觸發器,當刪除數據庫時,提示無法刪除,并回滾刪除操作。

1.	Create Trigger que5_1 on all server  
2.	after drop_database  
3.	as  
4.	print '不能刪除'  
5.	rollback transaction  
6.	drop database Hao  

???????

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/900396.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/900396.shtml
英文地址,請注明出處:http://en.pswp.cn/news/900396.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

子類是否能繼承

繼承 父類&#xff1a; 子 類 構造方法 非私有 不能繼承 私有&#xff08;private&#xff09;不能繼承 成員變量 非私有 能繼承 私有&…

2025年【山東省安全員C證】考試題及山東省安全員C證考試內容

在當今建筑行業蓬勃發展的背景下&#xff0c;安全生產已成為企業生存與發展的基石。安全員作為施工現場安全管理的直接責任人&#xff0c;其專業能力和資質認證顯得尤為重要。山東省安全員C證作為衡量安全員專業水平的重要標準&#xff0c;不僅關乎個人職業發展&#xff0c;更直…

Spring 中的 bean 生命周期

&#x1f331; 一、什么是 Bean 生命周期&#xff1f; 在 Spring 容器中&#xff0c;一個 Bean 從“創建 → 初始化 → 使用 → 銷毀”&#xff0c;經歷了完整的生命周期。 Spring 提供了 多個擴展點 讓你可以在這些階段做事情&#xff0c;比如注入資源、日志記錄、連接資源、清…

Media streaming mental map

Media streaming is a huge topic with a bunch of scattered technologies, protocols, and formats. You may feel like hearing fragments without seeing the big picture. Let’s build that mental map together — here’s a high-level overview that connects everyt…

AIDD-深度學習 MetDeeCINE 破譯代謝調控機制

深度學習 MetDeeCINE 破譯代謝調控機制 目錄 使用 FEP/REMD 和 DFT 方法準確預測藥物多靶點絕對結合自由能的新途徑。Scorpio 框架利用對比學習優化核苷酸序列表示&#xff0c;提升基因組分析效率&#xff0c;尤其在未知序列的分類和泛化能力上表現出色。LPM 模型整合多模態擾…

【2】搭建k8s集群系列(二進制)之安裝etcd數據庫集群

一、etcd服務架構 Etcd 是一個分布式鍵值存儲系統&#xff0c;Kubernetes 使用 Etcd 進行數據存儲&#xff0c;所以先 準備一個 Etcd 數據庫&#xff0c;為解決 Etcd 單點故障&#xff0c;應采用集群方式部署&#xff0c;這里使用 3 臺組建集群&#xff0c;可容忍 1 臺機器故障…

fastGPT—前端開發獲取api密鑰調用機器人對話接口(HTML實現)

官網文檔鏈接&#xff1a;OpenAPI 介紹 | FastGPT 首先按照文檔說明創建api密鑰 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-sca…

cpp自學 day19(多態)

一、基本概念 同一操作作用于不同的對象&#xff0c;產生不同的執行結果 &#x1f449; 就像「按F1鍵」&#xff1a;在Word彈出幫助文檔&#xff0c;在PS彈出畫筆設置&#xff0c;?同一個按鍵觸發不同功能 &#xff08;1&#xff09;多態類型 類型實現方式綁定時機?靜態多態…

Java 大視界 -- Java 大數據在航天遙測數據分析中的技術突破與應用(177)

&#x1f496;親愛的朋友們&#xff0c;熱烈歡迎來到 青云交的博客&#xff01;能與諸位在此相逢&#xff0c;我倍感榮幸。在這飛速更迭的時代&#xff0c;我們都渴望一方心靈凈土&#xff0c;而 我的博客 正是這樣溫暖的所在。這里為你呈上趣味與實用兼具的知識&#xff0c;也…

人臉考勤管理一體化系統(人臉識別系統,簽到打卡)

人臉考勤管理一體化系統 項目介紹 本項目是基于Flask、SQLAlchemy、face_recognition庫的人臉考勤管理一體化系統。 系統通過人臉識別技術實現員工考勤打卡、人臉信息采集、人臉模型訓練等功能。 項目采用前后端分離的技術框架&#xff0c;基于Flask輕量級Web框架搭建后端服務…

單調棧學習C++

目錄 一&#xff0c;每日溫度 二&#xff0c;下一個更大的元素I 三&#xff0c;下一個更大的元素II 四&#xff0c;接雨水 小結&#xff1a; 單調棧是一種特殊的棧結構&#xff0c;里面的元素按照單調遞增或者遞減的順序排列。常用于解決元素左邊或者右邊比它大或者小的問…

網絡釣魚攻擊的威脅和執法部門的作用(第一部分)

在當今的數字世界中&#xff0c;網絡犯罪分子不斷開發新技術來利用個人、企業和政府機構。 最普遍和最具破壞性的網絡犯罪形式之一是網絡釣魚——一種社會工程手段&#xff0c;用于欺騙人們提供敏感信息&#xff0c;例如登錄憑據、財務數據和個人詳細信息。 隨著網絡釣魚攻擊…

左值與右值,空間與數據

左值是空間&#xff0c;右值是數據 編程總是對“數據”&#xff0c;對"存放數據的空間"操作 a返回一個當前的數據&#xff0c;存放到一個臨時空間中&#xff0c;自身的空間中的數據再進行運算 a直接對自身空間中的數據進行運算 其余知識&#xff1a; 1.變量名的意…

無人機飛行術語科普!

一、基礎操作類 1. 炸機 指無人機意外墜毀或嚴重損壞&#xff08;如撞樹、撞樓、失控摔機等&#xff09;。 例句&#xff1a;“今天風太大&#xff0c;差點炸機&#xff01;” 2. 一鍵放生 調侃某些情況下無人機失控飛丟&#xff0c;無法找回&#xff08;源自某些品牌…

模擬算法(一):一維數組模擬

目錄 模擬的概念 例1&#xff1a;開關燈 算法思路&#xff1a; 代碼如下&#xff1a; 輸入輸出&#xff1a; 例2&#xff1a;序列操作和查詢 算法思路&#xff1a; 代碼如下&#xff1a; 輸入輸出&#xff1a; 例3&#xff1a;數組折疊 算法思路&#xff1a; 代碼如…

MySQL 基礎入門

寫在前面 關于MySQL的下載安裝和其圖形化軟件Navicat的下載安裝,網上已經有了很多的教程,這里就不再贅述了,本文主要是介紹了關于MySQL數據庫的基礎知識。 MySQL數據庫 MySQL數據庫基礎 MySQL數據庫概念 MySQL 數據庫&#xff1a; 是一個關系型數據庫管理系統 。 支持SQL語…

Qt中的多種輸出方式,信號與槽的基本使用

完成Hello World可以通過很多控件實現 如采用編輯框來完成hello world 編輯框分為單行編輯框----QLineEdit 和多行編輯框---QTextEdit 采用單行編輯框&#xff0c;創建項目后&#xff0c;展開forms文件夾&#xff0c;雙擊ui文件進入 qt designer設計頁面 找到line edit 拖到頁…

英語表達年代和世紀

英語表達年代和世紀 1. Century (世紀)1.1. Start and end of centuries 2. Decade (年代)2.1. Usage 3. 英語表達年代和世紀4. HomeworkReferences XXX0 年代指 XXX0 年 - XXX9 年的連續 10 年&#xff0c;例如 1760 年代指 1760 年至 1769 年這連續 10 年。 XX 世紀 X0 年代…

MySQL數據庫管理5

23.事務 1&#xff09;事務&#xff1a;可以認為是做一件事情 需要多個SQL 要么同時成功 要么同時失敗 需求&#xff1a;銀行轉賬update 你的賬戶 把你的錢減少update 你朋友的賬戶 把他的錢增多?這兩個SQL不能只成功一個 要么都成功 要么都失敗那么 我們就需要用到事務了 它…

閉包和裝飾器

什么是閉包 閉包&#xff08;Closure&#xff09;是 Python 中一個非常重要的概念&#xff0c;它是一種特殊的函數對象&#xff0c;通常用于封裝和延遲計算某些值。以下是閉包的詳細定義和解釋&#xff1a; 1.閉包的定義 閉包是指一個函數對象&#xff0c;它不僅包含函數的代…