存储过程详解

1,创建一个简单存储过程

示例:

create Procedure user --创建名为user存储过程
as  --指定过程要执行下面操作
select * from tablename
go

  

 2,调用存储过程 

示例:exec user 或者 execute user

执行后结果为:select * from tablename 查询的结果

3,修改存储过程

示例:alter Procedure 存储过程名

4,删除存储过程

示例:drop Procedure 存储过程名

5,带一个参数的存储过程

示例:

if (exists (select * from sys.objects where name = 'user'))  --如果有user这个存储过程
drop  Procedure user  --删除user
go
create Procedure user --创建user存储过程
(@UserID int)   --声明一个输入参数
as
select * from stud where studid=@UserID; --查询学生表中输入的userid的信息   
--执行user 存储过程
exec user 1;  --这里的1就是Userid 

  

6、创建带返回值的存储过程

示例:

if (exists (select * from sys.objects where name = 'user'))
drop Procedure user
go
create Procedure user(
@UserName varchar(20),--输入参数,无默认值
@UserId int output --输入/输出参数 无默认值,output 返回参数
)
as
select @UserId=studId from stud where studname=@UserName  --通过UserName找UserId
--执行User这个带返回值的存储过程
declare @id int --声明一个变量用来接收执行存储过程后的返回值
exec user '李四',@id output  --执行存储过程。@UserName=李四,@id output:返回值(UserId)
select @id as UserId ;--as是给返回的列值起一个名字

 7、带通配符的存储过程

示例:

create Procedure user(
@UserName varchar(20)='%'
@UserId int ='%'
)
as
select *from stud where studname like @UserName
and  studid like @UserId

exec user '李%','1%'  --匹配stud表中姓名李开头和id为1开头的学生信息

 8、带判断的存储过程

示例:

if (exists (select * from sys.objects where name = 'user'))
drop Procedure user
go
create Procedure user(
@a int,--输入参数,无默认值
@b int  --输入参数 无默认值,
)
as
if @a>@b
Begin  --if语句必须用Begin和end
   print 'a' --a>b,打印a
End
Else if @a<@b 
Begin
   print 'b'    --a<b,打印b
End
Else 
Begin
    print 'a=b'  --前两种情况都不满足,打印a=b
End
--执行调用存储过程
exec user 1,1  --这里a和b都是1,肯定打印a=b

  

原文地址:https://www.cnblogs.com/Lxxv5/p/14447625.html