SQL Server關於預存程序的一點簡單使用心得

來源:互聯網
上載者:User

標籤:

===========================建立無參無傳回值的預存程序===========================
create proc pro_name
as
--要執行的sql語句--
select * from tablename

--執行預存程序--
exec pro_name


===========================建立有參無傳回值的預存程序===========================
--帶參預存程序
create proc proc_find_stu(@startId int, @endId int)
as
select * from student where id between @startId and @endId

--執行預存程序
exec proc_find_stu 2, 4;

 

===========================有參有傳回值的預存程序===========================
create proc findUserNameByID
(
@uID int, --sql語句的條件參數
@uName varchar(100) output --帶output結尾的是要作為傳回值的參數
)
as
select @uName=USER_NAME from dbo.User_Info where User_ID = @uID

--執行
begin
declare @name varchar(100)
-- 此處假設是已知的id號
exec findUserNameByID 3654,@name output
select @name
end
--執行完成後輸出對應的使用者姓名

 

===========================分頁預存程序================================

-----------建立分頁預存程序--------------
create proc selectDivicebyPage
(
@pageIndex int,--頁碼
@pageSize int--單頁記錄條數
)
as

declare
--定義每頁的起始行數和終止行數
@startRow int=(@pageIndex-1)*@pageSize+1,
@endRow int = (@pageIndex-1)*@pageSize + @pageSize

--或者如下定義
--declare @startRow int, @endRow int
-- set @startRow = (@pageIndex - 1) * @pageSize +1
-- set @endRow = @startRow + @pageSize -1

--此處一次羅列出必須的列,不需要的列不羅列出來,從而提高查詢的執行速率
select User_ID,User_Name,User_Password,User_Email
from (select ROW_NUMBER() over(order by User_ID asc) as rownumber,* from dbo.User_Info) a
where a.rownumber between @startRow and @endRow


---------執行分頁預存程序------------
--頁碼為3,單頁10條記錄
exec selectDivicebyPage 3,10

 

===========================修改預存程序===========================

alter proc proc_get_student
as
select * from student;


===========================刪除預存程序===========================
DROP PROCEDURE Proc_name

 

SQL Server關於預存程序的一點簡單使用心得

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.