創建存儲過程


一、定義存儲過程的語法

語法:

CREATE PROC[EDURE] 存儲過程名

  @參數1 數據類型 = 默認值 OUTPUT,

  ......

  @參數n 數據類型 = 默認值 OUTPUT

AS

  SQL語句

GO

 

存儲過程的參數:

  • 和C#語言的方法一樣,參數可選
  • 參數分為輸入參數、輸出參數
  • 輸入參數允許有默認值

 

二、自定義存儲過程實例

1、需求

在StudentManageDB數據庫里有如下三張表,分別是學生表,成績表,班級表:

 

 現在有一個需求:查詢考試成績,顯示學號、姓名、班級、總成績、並按成績的總分高低排序。

可以使用存儲過程來解決:

 

2、新建存儲過程

use StudentManageDB
go
if exists(select * from sysobjects where name = 'usp_ScoreQuery')
drop procedure usp_usp_ScoreQuery
go
create procedure usp_ScoreQuery
as
    --查詢考試成績
    select Students.StudentId,StudentName,ClassName,ScoreSum=(CSharp + SQLServerDB) from Students
    inner join StudentClass on StudentClass.ClassId=Students.ClassId
    inner join ScoreList on Students.StudentId=ScoreList.StudentId
    order by ScoreSum desc
go

 

執行完畢,就可以在如下菜單中看到新建的存儲過程了:

 

3、調用存儲過程

exec usp_ScoreQuery

效果如下:

 

 

4、更新存儲過程

現在有一個新的需求,統計考試成績,顯示班級名稱、C#平均分、數據庫平均分,按照班級分組實現。

4.1、更新

use StudentManageDB
go
if exists(select * from sysobjects where name = 'usp_ScoreQuery')
drop procedure usp_usp_ScoreQuery
go
create procedure usp_ScoreQuery
as
    --查詢考試成績
    select Students.StudentId,StudentName,ClassName,ScoreSum=(CSharp + SQLServerDB) from Students
    inner join StudentClass on StudentClass.ClassId=Students.ClassId
    inner join ScoreList on Students.StudentId=ScoreList.StudentId
    order by ScoreSum desc

    --分析考試信息
    select ClassName,C#Avg=AVG(CSharp),DBAvg=AVG(SQLServerDB) from ScoreList
    inner join Students on Students.StudentId=ScoreList.StudentId
    inner join StudentClass on StudentClass.ClassId=Students.ClassId
    group by ClassName order by ClassName
go

 

4.2、調用

三、帶參數的存儲過程

use StudentManageDB
go
if exists(select * from sysobjects where name='usp_ScoreQuery2')
drop procedure usp_ScoreQuery2
go
--創建帶參數的存儲過程
create procedure usp_ScoreQuery2
@CSharp int=60,
@DB int=60
as
    select Students.StudentId, StudentName,C#=CSharp,DB=SQLServerDB from Students
    inner join ScoreList on Students.StudentId=ScoreList.StudentId
    where CSharp<@CSharp or SQLServerDB<@DB
go

--調用帶參數的存儲過程
exec usp_ScoreQuery2 60,65 --按照參數順序賦值
exec usp_ScoreQuery2 @DB=65,@CSharp=60 --參數順序可以調換
exec usp_ScoreQuery2 65  --第二個參數是默認值了
exec usp_ScoreQuery2 default,65 --第一個參數是默認值了
exec usp_ScoreQuery2 --倆個參數都是默認值了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM