当前位置: 移动技术网 > IT编程>数据库>MSSQL > sql存储过程详解

sql存储过程详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

李小鹏婚礼,wow天神悟道圣坛,0571.361.cm

1,不带参数的存储过程

2,带输入参数的存储过程

3,带输入和输出参数的存储过程

4,带返回值的存储过程

不带参数的存储过程

例如,以下存储过程返回employees表中所有职员的记录。

存储过程代码:

use tsqlfundamentals2008;
go

if object_id('usp_procdemonoparam','p') is not null drop proc usp_procdemonoparam;
go
-- 1,不带参数
create proc usp_procdemonoparam
as
begin
  select * from hr.employees;
end
go

调用代码:

use tsqlfundamentals2008;
go

-- 1,不带参数存储过程的调用
exec usp_procdemonoparam;

结果:

可以看到,共返回了9条记录。

带输入参数的存储过程

例如,该存储过程接受输入参数@empid,然后返回这个职员的信息。

创建存储过程代码:

if object_id('usp_procdemowithinputparam','p') is not null drop proc usp_procdemowithinputparam;
go
-- 2,带输入参数
create proc usp_procdemowithinputparam
  @empid as int
as
begin
  select * from hr.employees
  where empid= @empid;
end
go

调用:

-- 2,带输入参数存储过程调用
exec usp_procdemowithinputparam @empid=5;

结果:

带输入和输出参数的存储过程

例如,以下存储过程接受@empid即职员id作为输入参数,然后返回该职员的信息,同时返回代码受影响行数作为输出参数。

创建存储过程代码:

if object_id('usp_procdemowithinputoutputparam','p') is not null drop proc usp_procdemowithinputoutputparam;
go
-- 3,带输入和输出参数
create proc usp_procdemowithinputoutputparam
  @empid as int,
  @numrowsaffected as int output
as
begin
  select * from hr.employees
  where empid= @empid;
  
  set @numrowsaffected= @@rowcount; -- 赋值,也可以使用select赋值
end
go

调用:

-- 3,带输入和输出参数存储过程的调用
declare @nums as int;
exec usp_procdemowithinputoutputparam @empid=5,@numrowsaffected= @nums output;
select @nums as nums;

结果:

带返回值的存储过程

例如,以下存储过程接受@empid即职员id作为输入参数,然后判断职员表中是否存在该职员的记录,如果存在则返回1,否则返回0.

创建存储过程代码:

if object_id('usp_procdemowithreturnvalue','p') is not null drop proc usp_procdemowithreturnvalue;
go
-- 4,带返回值
create proc usp_procdemowithreturnvalue
  @empid as int
as
begin
  if exists (select * from hr.employees where empid=@empid)
    return 1
  else
    return 0; -- 也可以声明一个变量,然后返回这个变量
end
go

调用:

-- 4,带返回值存储过程的调用
declare @status as int=0; --给默认值为0
exec @status= dbo.usp_procdemowithreturnvalue @empid = 5 -- int
select @status as thestatus;

结果:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网