一、存儲過程與函數的區別:
1.一般來說,存儲過程實現的功能要複雜一點,而函數的實現的功能針對性比較強。
2.對於存儲過程來說可以返回參數(output),而函數只能返回值或者表對象。
3.存儲過程一般是作爲一個獨立的部分來執行,而函數可以作爲查詢語句的一個部分來調用,由於函數可以返回一個表對象,因此它可以在查詢語句中位於FROM關鍵字的後面。
二、存儲過程的優點:
1.執行速度更快 – 在數據庫中保存的存儲過程語句都是編譯過的
2.允許模塊化程序設計 – 類似方法的複用
3.提高系統安全性 – 防止SQL注入
4.減少網絡流通量 – 只要傳輸存儲過程的名稱
系統存儲過程一般以sp開頭,用戶自定義的存儲過程一般以usp開頭
三、定義存儲過程語法,"[" 裏面的內容表示可選項
create proc 存儲過程名
@參數1 數據類型 [=默認值] [output],
@參數2 數據類型 [=默認值] [output],
...
as
SQL語句
四、簡單的一個例子
定義存儲過程:
create proc usp_StudentByGenderAge
@gender nvarchar(10) [='男'],
@age int [=30]
as
select * from MyStudent where FGender=@gender and FAge=@age
執行存儲過程:
Situation One(調用默認的參數):
exec usp_StudentByGenderAge
Situation Two(調用自己指定的參數):
exec usp_StudentByGenderAge '女',50
或者指定變量名 exec usp_StudentByGenderAge @age=50,@gender='女'
對存儲過程進行修改
alter proc usp_StudentByGenderAge
@gender nvarchar(10) [='男'],
@age int [=30],
--加output表示該參數是需要在存儲過程中賦值並返回的
@recorderCount int output
as
select * from MyStudent where FGender=@gender and FAge=@age
set @recorderCount=(select count(*) from MyStudent where FGender=@gender and FAge=@age)
--output參數的目的,就是調用者需要傳遞一個變量進來,然後在存儲過程中爲該變量完成賦值工作,存儲過程執行完成以後,將執行的對應結果返回給傳遞進來的變量。(與C#中的out原理一模一樣)
調用(記住這裏的語法!)因爲該存儲過程前面還有其他參數,所以要把 @recorderCount寫上,該存儲過程執行後,相當與完成了以上的查詢工作,同時將查詢結果得到的條數賦值給了@count變量。(@count是當做參數傳給usp_StudentByGenderAge,當存儲過程執行完畢以後,將得到的條數返回給@count)
declare @count int
exec usp_StudentByGenderAge @recorderCount=@count output
print @count
五、使用存儲過程完成分頁
1、存儲過程代碼
create proc usp_page
@page int, ---一頁顯示多少條記錄
@number int, ---用戶選擇了第幾頁數據
as
begin
select * from
--小括號裏面內容是專門得到排列好的序號
(
select ROW_NUMBER() over(order by(Fid)) as number
from MyStudent
) as t
where t.number>= (@number-1)*@page+1 and t.number<=@number*@page
end
2、實現分頁效果對應的ADO.NET代碼:
1 private void button1_Click(object sender, EventArgs e)
{
2 string connStr = @"server=.\sqlexpress;database=MyDB;integrated security=true";
3 using (SqlConnection conn = new SqlConnection(connStr))
4 {
5 //打開數據庫連接
6 conn.Open();
7 //用存儲過程名作爲Command處理的對象
8 string usp = "usp_page";
9 using (SqlCommand cmd = new SqlCommand(usp, conn))
10 {
11 //執行的是存儲過程語句
12 cmd.CommandType = CommandType.StoredProcedure;
//textBox1.Text是指顯示多少條記錄
13 cmd.Parameters.AddWithValue("@page", textBox1.Text.Trim());
14 //textBox.Text是指用戶選擇了第幾頁
15 cmd.Parameters.AddWithValue("@number", textBox2.Text.Trim());
16 //用list作爲數據源來實現
17 List<Person> p = new List<Person>();
18 using (SqlDataReader reader = cmd.ExecuteReader())
19 {
20 if (reader.HasRows)
21 {
22 while (reader.Read())
24 {
25 Person p1 = new Person();
26 p1.FName = reader.GetString(1);
27 p1.FAge = reader.GetInt32(2);
28 p1.FGender = reader.GetString(3);
29 p1.FMath = reader.GetInt32(4);
30 p1.FEnglish = reader.GetInt32(5);
31 p.Add(p1);
32 }
33 }
34 }
35 dataGridView1.DataSource = p;
36 }
37 }
38 }