存储过程的简单使用(一)

存储过程的分类

1.系统存储过程

系统存储过程是 SQL Server系统自身提供的存储过程,可以作为命令执行各种操作。
系统存储过程创建并存放在与系统数据库master中,一些系统存储过程只能由系统管理员使用,而有些系统存储过程通过授权可以被其它用户所使用。

系统存储过程主要用来从系统表中获取信息,使用系统存储过程完成数据库服务器的管理工作,为系统管理员提供帮助,为用户查看数据库对象提供方便,系统存储过程位于数据库服务器中,并且以sp_开头,系统存储过程定义在系统定义和用户定义的数据库中,在调用时不必在存储过程前加数据库限定名。
例如:sp_rename系统存储过程可以修改当前数据库中用户创建对象的名称,sp_helptext存储过程可以显示规则。

2.用户存储过程(自定义存储过程)

自定义存储过程即用户使用T_SQL语句编写的、为了实现某一特定业务需求,在用户数据库中编写的T_SQL语句集合,自定义存储过程可以接受输入参数、向客户端返回结果和信息,返回输出参数等。

用户定义的存储过程分为两类:T_SQL 和CLR

T_SQL:存储过程是值保存的T_SQL语句集合,可以接受和返回用户提供的参数,存储过程也可能从数据库向客户端应用程序返回数据。

CLR存储过程是指引用Microsoft.NET Framework公共语言的方法存储过程,可以接受和返回用户提供的参数,它们在.NET Framework程序集是作为类的公共静态方法实现的。

存储过程的创建

准备数据 如下:

–创建测试表
create table testTable(
id int identity(1,1) primary key,
money int
);
–插入若干条测试数据
truncate table testTable
insert into testTable Values(21)
insert into testTable Values(22)
insert into testTable Values(23)
insert into testTable Values(24)
select * from testTable

1.创建一个无参存储过程

if exists(select * from sysobjects where name=‘sp_gettestTable’)
//查询是否存在sp_gettestTable这个存储过程
drop proc sp_gettestTable
go
创建存储过程 create proc sp_gettestTable

执行存储过程 exec sp_gettestTable

删除存储过程 drop proc sp_gettestTable

修改存储过程 alter procedure sp_gettestTable

2.创建一个带参数的存储过程 并执行

创建带一个参数的存储过程
create proc sp_gettestTable
@id int
as
select * from testTable where id=@id
go

–调用后面添加参数
exec sp_gettestTable 3

3.创建一个带output参数的存储过程 并执行
create proc sp_gettestTable
@count int output
as
set @count = (select count(*) from testTable)
go

declare @icount int; //定义变量接收返回值
exec sp_gettestTable @count=@icount output --在调用的时候 要加output的关键字-
print @icount

猜你喜欢

转载自blog.csdn.net/q1923408717/article/details/99836564