首页 > 解决方案 > 执行应该返回 int 的存储过程

问题描述

我有一个存储过程,它需要几个输入参数并返回一个整数:

CREATE procedure [dbo].[HB_ValidateLogin_HitAlacarte]
(
    @Login nvarchar(50),
    @Pwd nvarchar(50),
    @Vat int, 
    @Page  nvarchar(50)
)
as
Begin
    return -3 --- too many Badlogins 
End

我使用 Entity Framework 调用这个存储过程:

try
{
    string sqlQuery = "exec [dbo].[HB_ValidateLogin_HitAlacarte] @Login, @Pwd, @Vat, @Page";

    var outParam = new SqlParameter();
    outParam.ParameterName = "@return_value";
    outParam.SqlDbType = System.Data.SqlDbType.BigInt;
    outParam.Direction = System.Data.ParameterDirection.Output;

    SqlParameter[] sqlParams = new SqlParameter[]
    {
        new SqlParameter { ParameterName = "@Login",  Value =initRequest.Login, Direction = System.Data.ParameterDirection.Input},
        new SqlParameter { ParameterName = "@Pwd",  Value =initRequest.Pwd, Direction = System.Data.ParameterDirection.Input },
        new SqlParameter { ParameterName = "@Vat",  Value =initRequest.VatNumber, Direction = System.Data.ParameterDirection.Input},
        new SqlParameter { ParameterName = "@Page",  Value =initRequest.Page, Direction = System.Data.ParameterDirection.Input},
        outParam
    };

    using (xmlALaCarteContext)
    {
        List<List<int>> result = xmlALaCarteContext.Database.SqlQuery<List<int>>(sqlQuery, sqlParams).ToList();
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.StackTrace);
    Console.ReadLine();
}

但是,当我运行代码时,我从来没有得到-3。我的 outParam 始终具有 null 值。我究竟做错了什么?我正在使用 EntityFramework 版本 6.0.0.0

标签: stored-proceduresentity-framework-6

解决方案


您需要@return_value在存储过程中将您声明为 OUTPUT 参数,然后设置它而不是调用 RETURN

CREATE procedure [dbo].[HB_ValidateLogin_HitAlacarte] (
    @Login nvarchar(50),
    @Pwd nvarchar(50),
    @Vat int, 
    @Page  nvarchar(50),
    @return_value int OUTPUT
)

或更改您的 exec 语句,以便它处理返回值,但我不确定与您的框架一起使用的正确语法,但类似于

string sqlQuery = "exec @return_value =[dbo].[HB_ValidateLogin_HitAlacarte]..."

推荐阅读