output输出标识
output标记一般用于存储过程中输出多个变量的过程或返回为非整数值。
案例1:根据班级和性别查询学员,同时返回总人数和指定性别的人数
if exists (select * from sysobjects where name = 'usp_getSInfoAndCount')
drop proc usp_getSInfoAndCount
go
create proc usp_getSInfoAndCount
@totalNum int output,--如果一个参数添加了output修饰,那么说明:它是一个输出参数。
--标明了output说明了你会向服务器请求返回这个参数的值。而服务器也知道标识了output的参数在以后需要返回
@claNum int output, --指定班级和性别的总人数
@className nvarchar(50),
@sex char(1) = '1'
as
declare @cid int = (select GradeId from grade where GradeName = @className)
select * from student where GradeId = @cid and Gender = @sex
set @totalNum = (select count(*) from student) --总学生人数,赋值给参数@totalNum
set @claNum = (select count(*) from student where GradeId = @cid and gender = @sex)--返回班级和性别查询学员,并赋值给参数@claNum
go
-调用在输出参数的过程中
–服务器向你返回值,用户就需要创建对应的变量做接收
–标明了output说明了你会向服务器请求返回这个参数的值,而服务器也知道标识了output的参数在以后需要返回
declare @tNum int,@cNum int
exec usp_getSInfoAndCount @tNum output,@cNum output,'社会大学1' --调用存储过程也需要把output修饰带上
print @totalNum
print @claNum
print 'ok'
输出结果:
案例2:–返回指定学员名字
if exists(select * from sysobjects where name = 'usp_getNameByNo')
drop proc usp_getNameByNo
go
create proc usp_getNameByNo
@stuNo int
as
declare @name nvarchar(50)
set @name = (select StudentName from student where StudentNo = @stuNo)
return @name --存储过程中的ruturn只能返回整数值
go
调用存储过程:返回指定学员姓名
exec usp_getNameByNo 10001
显示结果
因为ruturn的返回结果只能是整型,而@name定义的为字符型,过字符转换报错,返回为非整型的存储过程建议使用output标识