存储过程返回不正确的标量值 -1,而不是返回值 [英] Stored Procedure returns incorrect scalar value of -1, instead of return value

查看:18
本文介绍了存储过程返回不正确的标量值 -1,而不是返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

  1. change your procedure so that it doesn't return the value, but selects it, i.e. instead of RETURN @return do SELECT @return AS alias. NOTE that you need the "AS alias" part. The alias can be whatever column name you want.
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆