---------------创建自己的存储过程-----------------
```sql
create proc usp_sayHello
as
begin
print '你好,张慧鑫!'
end
exec usp_sayHello --调用
---------------创建带参数的存储过程----------
–参数可以设置默认值,传参时若没有标参数名会按顺序传参,传参会覆盖默认值
create proc usp_sum
@i int,
@j int
as
begin
select @i+@j
end
exec usp_sum 1,2 --调用
create proc usp_select
@caId int
as
begin
select * from news where caID=@caId
end
exec usp_select @caId=62 --调用
----------带输出参数的存储过程---------
–需要多种返回值时–
create proc usp_output
@caId int,
@count int output--输出参数
as
begin
select * from news where caID=@caId
set @count=(select count(*) from news where caID=@caId)
end
--调用
declare @rcount int--创建一个变量承载输出参数的结果
exec usp_output 3,@count=@rcount output--传参,绑定输出参数与变量,设定output
print @rcount
------------存储过程实现分页----------
set nocount off--设置是否需要显示受影响的行数
create proc usp_loadPage
@pageSize int=5,--默认每页条数
@pageIndex int=1,--需要查询的页数
@pageCount int output--可以查询的总页数
as
begin
select *
from
(select *,rn=ROW_NUMBER() over(order by ID asc)from news) as t
where
t.rn>(@pageIndex-1)*@pageSize
and
t.rn<=(@pageIndex)*@pageSize
set @pageCount=ceiling((select count(*) from news)*1.0/@pageSize)
end
declare @pages int
exec usp_loadPage @pageIndex=2,@pageCount=@pages output --调用
----------报错---------
--不是批处理中仅有的语句:
-- 原因:创建存储过程的语句必须独立执行,不能与其他语句同时执行
-- 解决:在CREATE之前加 go
--超出最大嵌套层数
-- 原因:创建存储过程的时候把调用的语句也写了进去
-- 解决:修改存储过程