您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 质量控制/管理 > SQLServer存储过程返回值总结
1.存储过程没有返回值的情况(即存储过程语句中没有return之类的语句)用方法intcount=ExecuteNonQuery(..)执行存储过程其返回值只有两种情况(1)假如通过查询分析器执行该存储过程,在显示栏中假如有影响的行数,则影响几行count就是几(2)假如通过查询分析器执行该存储过程,在显示栏中假如显示'命令已成功完成。'则count=-1;在显示栏中假如有查询结果,则count=-1总结:A.ExecuteNonQuery()该方法只返回影响的行数,假如没有影响行数,则该方法的返回值只能是-1,不会为0。B.不论ExecuteNonQuery()方法是按照CommandType.StoredProcedure或者CommandType.Text执行,其效果和A一样。---------------------------------------------------------------------------------------------------------------------------------------------------2.获得存储过程的返回值--通过查询分析器获得(1)不带任何参数的存储过程(存储过程语句中含有return)---创建存储过程CREATEPROCEDUREtestReturnASreturn145GO---执行存储过程DECLARE@RCintexec@RC=testReturnselect@RC---说明查询结果为145(2)带输入参数的存储过程(存储过程语句中含有return)---创建存储过程createproceduresp_add_table1@in_namevarchar(100),@in_addrvarchar(100),@in_telvarchar(100)asif(@in_name=''or@in_nameisnull)return1elsebegininsertintotable1(name,addr,tel)values(@in_name,@in_addr,@in_tel)return0end---执行存储过程1执行下列,返回1declare@countintexec@count=sp_add_table1'','中三路','123456'select@count2执行下列,返回0declare@countintexec@count=sp_add_table1'','中三路','123456'select@count---说明查询结果不是0就是1(3)带输出参数的存储过程(存储过程中可以有return可以没有return)例子A:---创建存储过程createproceduresp_output@outputintoutputasset@output=121return1---执行存储过程1执行下列,返回121declare@outintexecsp_output@outoutputselect@out2执行下列,返回1declare@outintdeclare@countintexec@count=sp_output@outoutputselect@count---说明有return,只要查询输出参数,则查询结果为输出参数在存储过程中最后变成的值;只要不查询输出参数,则查询结果为return返回的值例子B:---创建存储过程createproceduresp_output@outputintoutputasset@output=121---执行存储过程1执行下列,返回121declare@outintexecsp_output@outoutputselect@out2执行下列,返回0declare@outintdeclare@countintexec@count=sp_output@outoutputselect@count---说明没有return,只要查询输出参数,则查询结果为输出参数在存储过程中最后变成的值;只要不查询输出参数,则查询结果为0总结:(1)存储过程共分为3类:A.返回记录集的存储过程---------------------------其执行结果是一个记录集,例如:从数据库中检索出符合某一个或几个条件的记录B.返回数值的存储过程(也可以称为标量存储过程)-----其执行完以后返回一个值,例如:在数据库中执行一个有返回值的函数或命令C.行为存储过程-----------------------------------用来实现数据库的某个功能,而没有返回值,例如:在数据库中的更新和删除操作(2)含有return的存储过程其返回值为return返回的那个值(3)没有return的存储过程,不论执行结果有无记录集,其返回值是0(4)带输出参数的存储过程:假如有return则返回return返回的那个值,假如要select输出参数,则出现输出参数的值,于有无return无关---------------------------------------------------------------------------------------------------------------------------------------------------3.获得存储过程的返回值--通过程序获得---------------------------------------------------------------------------------------------------------------------------------------------------SqlParameter[]cmdParms={..,newSqlParameter(@return,SqlDbType.Int)};cmdParms[cmdParms.Length-1].Direction=ParameterDirection.ReturnValue;或者cmdParms[cmdParms.Length-1].Direction=ParameterDirection.Output或者cmdParms[cmdParms.Length-1].Direction=ParameterDirection.Input;得到返回值objectbj=cmdParms[cmdParms.Length-1].Value;
本文标题:SQLServer存储过程返回值总结
链接地址:https://www.777doc.com/doc-2860249 .html