国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

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

分享Sql Server 存儲(chǔ)過程使用方法

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

一、簡介

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

二、使用

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

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

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

exec getGroup 7000

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

3.1 要實(shí)現(xiàn)分頁,首先要知道實(shí)現(xiàn)的原理,其實(shí)就是查詢一個(gè)表中的前幾條數(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 當(dāng)查詢第三頁時(shí),肯定不需要前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ù)化,寫成存儲(chǔ)過程如下

create proc sp_pager
(
? ? @size int , --每頁大小
? ? @index int --當(dāng)前頁碼
)
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 當(dāng)前的這種寫法,要求id必須連續(xù)遞增,所以有一定的弊端

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

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 存儲(chǔ)過程使用方法的文章就介紹到這了,更多相關(guān)Sql Server 存儲(chǔ)過程內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!

標(biāo)簽: MsSQL
相關(guān)文章:
主站蜘蛛池模板: 太湖县| 黄平县| 潮州市| 涿州市| 东光县| 房山区| 凤翔县| 邯郸市| 齐河县| 喀什市| 大庆市| 霍邱县| 平和县| 论坛| 聂荣县| 石城县| 扶沟县| 那曲县| 盐津县| 正宁县| 柘城县| 巴林左旗| 垦利县| 洮南市| 汶川县| 济阳县| 龙川县| 海林市| 新安县| 兴仁县| 靖边县| 平罗县| 平遥县| 张北县| 恭城| 修武县| 阜新市| 惠来县| 宜兴市| 博客| 铅山县|