存储过程不输出结果
本文关键字:结果 输出 存储过程 | 更新日期: 2023-09-27 18:25:50
作为学习Stored procedures
的一部分,我想出了这个。
CREATE PROCEDURE StoredProcedure1
@oResult int output
AS
BEGIN
SELECT @oResult = 2
RETURN @oResult
END
- 但问题出在这个SP的执行上,它只是返回类似的内容。
Procedure or function 'StoredProcedure1' expects parameter '@oResult', which was not supplied.
我希望此过程在调用时只返回一个结果
有什么想法吗?
- 我按照它的要求提供了
EXEC StoredProcedure1 @oResult = 0
,但它只是说Command Completed Successfully
,但没有输出
有什么想法吗?
在ADO.NET中,当您调用一个需要参数的存储过程时,您需要给出该参数,如果它是输出参数,也需要提供该参数。
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand("StoredProcedure1", cnn))
{
cnn.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = new SqlParameter("@oResult", SqlDbType.Int);
p.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();
int result = Convert.ToInt32(cmd.Parameters["@oResult"].Value);
}
当然,在存储过程中,您应该按照其他答案中解释的方式设置@oResult参数,但如果使用OUTPUT参数,则不需要返回相同的值。
但是,如果需要的话,可以同时使用OUTPUT参数和RETURN值
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand("StoredProcedure1", cnn))
{
cnn.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = new SqlParameter("@oResult", SqlDbType.Int);
p.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p);
// Here the name @returnValue is arbitrary, you could call it whatever you like
SqlParameter r = new SqlParameter("@returnValue", SqlDbType.Int);
r.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(r);
cmd.ExecuteNonQuery();
int result = Convert.ToInt32(cmd.Parameters["@oResult"].Value);
int returnValue = Convert.ToInt32(cmd.Parameters["@returnValue"].Value);
}
但请记住,RETURN值仅限于Integer表达式。
您可以这样做:
存储过程
CREATE PROCEDURE StoredProcedure1
@oResult int output
AS
BEGIN
SET @oResult = 2
END
然后这样称呼它:
DECLARE @Result INT
exec StoredProcedure1 @oResult = @Result output
SELECT @Result
这将输出
2
更新:
如评论中所述。您也可以简化语句。这样做:
DECLARE @Result INT
exec StoredProcedure1 @Result output
SELECT @Result
参考:
- 是否使用Output参数执行存储过程
您不需要编写return。。尝试以下代码:-
CREATE PROCEDURE StoredProcedure1
@oResult int output
AS
BEGIN
SET @oResult = 2
END
CREATE PROCEDURE SP1
(
@oResult int output
)
AS
BEGIN
SET @oResult=2
Select @oResult
END