存储过程返回不正确的标量值 -1,而不是返回值 [英] Stored Procedure returns incorrect scalar value of -1, instead of return value
问题描述
I am trying to return a scalar value from a stored procedure. I actually want to return the ID of a newly created record, but I have simplified my problem down to a stored procedure that takes an int
and attempts to return that same int
. This always returns -1. Thank you very much for your help.
Web API Controller call
var idtest = dbconn.my_return_int(123);
The stored procedure:
ALTER PROCEDURE [dbo].[my_return_int]
@ID int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @return as int
SET @return = -999
RETURN @return
END
The Context
generated stored procedure call
public virtual int my_return_int(Nullable<int> iD)
{
var iDParameter = iD.HasValue ?
new ObjectParameter("ID", iD) :
new ObjectParameter("ID", typeof(int));
return (IObjectContextAdapter)this).ObjectContext.ExecuteFunction("my_return_int", iDParameter);
}
When you execute ObjectContext.ExecuteFunction
the result is:
from MSDN: discards any results returned from the function; and returns the number of rows affected by the execution
I.e. it doesn't return the output parameter, because it doesn't know there is one. Besides, as you have called SET NOCOUNT ON;
in your stored procedure, it doesn't even return the number of affected rows, thus you get the -1.
So, you must do two changes:
- change your procedure so that it doesn't return the value, but selects it, i.e. instead of
RETURN @return
doSELECT @return AS alias
. NOTE that you need the "AS alias" part. Thealias
can be whatever column name you want. - change the mapping of the stored procedure, so that it expects an
int32
value. If you have doubt, refer to this Q&A.
In this way you'll read the return value as a result set, instead of a return value.
这篇关于存储过程返回不正确的标量值 -1,而不是返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!