存储过程

//sp_和xp_开头的是系统存储过程:系统的存储过程不用加exec,自己写的存储过程才需要exec,一般自己创建的存储过程命名是usp_开头

//查看自己的存储过程:数据库==》可编程性==》存储过程

create proc usp_helloworld---------创建存储过程(存储过程,顾名思义就是存储sql语句执行过程,类似一个方法)
as
begin -----------------------------begin相当于{
  print 'HELLO WORLD' --------------------------这里一般就是自定义的sql语句
end -----------------------------end相当于}

exec usp_helloworld ------------------调用存储过程exec 

drop proc usp_helloworld -------------删除存储过程drop proc 
alter proc usp_helloworld ------------修改存储过程alter proc

例子:

创建:

create proc usp_select_zgqx
as
begin
  select * from dbo.Table_1
end

---------------带参数的存储过程---------
create proc usp_myselect_cs
@n1 int, --------------------------------@开头,后跟参数名称,空格跟参数类型
@n2 int-------------------------------------如果@n2 int=10,这样就表示默认值,当没有传入参数时候就使用它

as
begin
select @n1+@n2 -------------------直接使用参数名
end

exec usp_myselect_cs 100,200 --------------调用时候存储过程名称后面,空格传入参数,以逗号分开

exec usp_myselect_cs @n1=100,@n2=200 --------------也可以这样写,更明了,这种写法更加严谨,不易出错,建议用这种

调用:
exec usp_select_zgqx

------------------------带输出参数的存储过程---------------------
create proc usp_myselect_cs2
@n1 int ,
@n2 int output--------------------可以多个
as
begin
set @n2=(select @n1)
end

declare @csn2 int --------------------------------------------声明变量@csn2
exec usp_myselect_cs2 @n1=10,@n2=@csn2 output ---------------传入变量@n2=@csn2 output
print @csn2

---------------带输出参数的分页查询----------------------

go ----------------------------------------------------------------一起执行多条过程时候,要在前面加上Go不然会报错滴
create proc usp_pageEach -------------过程名称usp_pageEach 
  @pagesize int ,-------------每页记录数
  @pageIndex int,----------------当前页码
  @recordcount int output,-----------记录数
  @pagecount int output ------------总页数
as
begin
select
  t.国家,
  t.首都,
  t.军队数量
  from(select *,rn=ROW_NUMBER() over(order by 序列号 asc) from dbo.Table_1) as t ----------给查询结果加一列按知道字段排序的标号
  where t.rn between (@pageIndex-1)*@pagesize+1 and @pagesize*@pageIndex ------------页码范围效果:0- 7,8- 14,15-21
  set @recordcount=(select COUNT(*) from dbo.Table_1) ----------总记录条数
  set @pagecount=ceiling(@recordcount*1.0/@pagesize)-----------向上取整数
end
--调用--
declare @count int,@pgcount int
exec usp_pageEach 3,2,@recordcount=@count output,@pagecount=@pgcount output
print @count
print @pgcount

 

posted @ 2016-08-03 17:39  黑色鼠标  阅读(182)  评论(0编辑  收藏  举报