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;
结果: