成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

分享Sql Server 存儲過程使用方法

瀏覽:189日期:2023-03-06 14:25:38
目錄
  • 一、簡介
  • 二、使用
  • 三、在存儲過程中實現(xiàn)分頁

一、簡介

簡單記錄一下存儲過程的使用。存儲過程是預(yù)編譯SQL語句集合,也可以包含一些邏輯語句,而且當?shù)谝淮握{(diào)用存儲過程時,被調(diào)用的存儲過程會放在緩存中,當再次執(zhí)行時,則不需要編譯可以立馬執(zhí)行,使得其執(zhí)行速度會非???。

二、使用

創(chuàng)建格式    create procedure 過程名( 變量名     變量類型 ) as    begin   ........    end 

create procedure getGroup(@salary int)
as
begin
? ?SELECT d_id AS "部門編號", AVG(e_salary) AS "部門平均工資" FROM employee
  GROUP BY d_id?
  HAVING AVG(e_salary) > @salary
end ? ??

調(diào)用時格式,exec 過程名  參數(shù)

exec getGroup 7000

三、在存儲過程中實現(xiàn)分頁

3.1 要實現(xiàn)分頁,首先要知道實現(xiàn)的原理,其實就是查詢一個表中的前幾條數(shù)據(jù)

select top 10 * from table ?--查詢表前10條數(shù)據(jù)?
select top 10 * from table where id not in (select top (10) id ?from tb) --查詢前10條數(shù)據(jù) ?(條件是id 不屬于table 前10的數(shù)據(jù)中)

3.2 當查詢第三頁時,肯定不需要前20 條數(shù)據(jù),則可以

select top 10 * from table where id not in (select top ((3-1) * 10) id ?from tb) --查詢前10條數(shù)據(jù) ?(條件是id 不屬于table 前10的數(shù)據(jù)中)

3.3 將可變數(shù)字參數(shù)化,寫成存儲過程如下

create proc sp_pager
(
? ? @size int , --每頁大小
? ? @index int --當前頁碼
)
as
begin
? ? declare @sql nvarchar(1000)
? ? if(@index = 1)?
? ? ? ? set @sql = "select top " + cast(@size as nvarchar(20)) + " * from tb"
? ? else?
? ? ? ? set @sql = "select top " + cast(@size as nvarchar(20)) + " * from tb where id not in( select top "+cast((@index-1)*@size as nvarchar(50))+" id ?from tb )"
? ? execute(@sql)
end

 3.4 當前的這種寫法,要求id必須連續(xù)遞增,所以有一定的弊端

所以可以使用 row_number(),使用select語句進行查詢時,會為每一行進行編號,編號從1開始,使用時必須要使用order by 根據(jù)某個字段預(yù)排序,還可以使用partition by 將 from 子句生成的結(jié)果集劃入應(yīng)用了 row_number 函數(shù)的分區(qū),類似于分組排序,寫成存儲過程如下

create proc sp_pager
(
? ? @size int,
? ? @index int
)
as
begin
? ? select * from ( select row_number() over(order by id ) as [rowId], * from table) as b
? ? where [rowId] between @size*(@index-1)+1 ?and @size*@index
end

到此這篇關(guān)于分享Sql Server 存儲過程使用方法的文章就介紹到這了,更多相關(guān)Sql Server 存儲過程內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!

標簽: MsSQL
相關(guān)文章: