15

this returns -1, how can i get the actual return value from stored procedure?

here is my stored procedure

ALTER PROCEDURE [Production].[Select_TicketQuantity]
    @Ticket NVARCHAR(25),
    @Reference NVARCHAR(20)
AS
BEGIN

    declare @SQL nvarchar (4000)
    SET @SQL = 'select QARTCOL as Quantidade from D805DATPOR.GCARCCR1 where NCOLGIA = ' + @Ticket + ' AND NARTCOM = ''' + @Reference + ''''
    SET @SQL = N'select CONVERT(int,Quantidade) as Quantidade from OpenQuery(MACPAC, ''' + REPLACE(@SQL, '''', '''''') + ''')'
    PRINT @SQL
    EXEC (@SQL)

END   

C# code

int? quantity= 0;
try
{
    quantity= await _context.Database.ExecuteSqlRawAsync("EXEC Production.Select_TicketQuantity @p0, @p1", parameters: new[] { ticket, reference});
}
catch (Exception ex)
{
    _logger.LogError($"{ex}");
    return RedirectToPage("Index");
}
1
  • 1
    Consider to mark or to share the solution for it... Apr 3, 2020 at 23:19

7 Answers 7

22

ExecuteSqlRawAsync returns the number of rows affected for inserts, updates and deletes (-1 for selects).

If you don't want to alter your SP to introduce the output parameter you can use SqlCommand. SqlCommand.ExecuteScalar() returns The first column of the first row in the result set:

using (var cmd = _context.Database.GetDbConnection().CreateCommand()) {
    cmd.CommandText = "[Production].[Select_TicketQuantity]";
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    if (cmd.Connection.State != System.Data.ConnectionState.Open) cmd.Connection.Open();
    cmd.Parameters.Add(new SqlParameter("Ticket", ticket));
    cmd.Parameters.Add(new SqlParameter("Reference", reference));
    quantity = (int)cmd.ExecuteScalar();
}
0
9

You need to create and use an output parameter, in your case:

ALTER PROCEDURE [Production].[Select_TicketQuantity]
    @Ticket NVARCHAR(25),
    @Reference NVARCHAR(20),
    @Quantity int output
AS
BEGIN

declare @SQL nvarchar(4000) = 'select QARTCOL as Quantidade from D805DATPOR.GCARCCR1 where NCOLGIA = ''' + @Ticket + ''' AND NARTCOM = ''' + @Reference + ''''
select @Quantity = CONVERT(int, Quantidade)
  from OpenQuery(MACPAC, @SQL)

END   

Then in C#:

int? quantity = 0;
var ticketParam = new SqlParameter("Ticket", ticket);
var referenceParam = new SqlParameter("Reference", reference);
var quantityParam = new SqlParameter("Quantity") { Direction = ParameterDirection.Output };
try
{
    await _context.Database.ExecuteSqlRawAsync("EXEC Production.Select_TicketQuantity @Ticket, @Reference, @Quantity output", new[] { ticketParam, referenceParam, quantityParam });
    quantity = Convert.ToInt32(quantityParam.Value);
}
catch (Exception ex)
{
    _logger.LogError($"{ex}");
    return RedirectToPage("Index");
}
2
  • this solution looks interesting but says invalid column on Quantidade at the convert and that expects a string at the @SQL in From Openquery
    – Jackal
    Jan 7, 2020 at 10:03
  • You can replace the text in the sproc with the original content, that was me doing a bit of playing.
    – Ian Kemp
    Jan 8, 2020 at 9:37
5

To add to what AlbertK already has written but by using ExecuteSqlRaw/ExecuteSqlRawAsync.

The best bet is to use OUTPUT parameter in your Stored Procedure.

Imagine a scenario where reading the StatusCode from a stored procedure is a necessity:

CREATE PROCEDURE dbo.spIfUserExists (
    @Username VARCHAR(120),
    @StatusCode INT OUTPUT,
) AS
BEGIN
    IF EXISTS (SELECT * FROM dbo.[Users] WHERE Username=@Username)
        SET @StatusCode = 1;
    ELSE
        SET @StatusCode = 0;
END

You are not really returning anything but assigning an integer(INT) to the output parameter which will be available outside.

In your C# code, you need to create SQLParameter object with the output parameter name from your stored procedure.

SqlParameter StatusCode = new SqlParameter
{
    ParameterName = "@StatusCode",
    SqlDbType = System.Data.SqlDbType.Int,
    //Direction of this parameter is output.
    Direction = System.Data.ParameterDirection.Output
 };

Finally, execute ExecuteSqlRawAsync with the required parameters for your SP.

Where @p0,@p1..@pn indicates the positional arguments of your stored procedure.

string Username = "MyRandomUsername";

using (var ctx = new UsersDbContext())
{
    await ctx.Database.ExecuteSqlRawAsync(
      "spIfUserExists @p0, @StatusCode OUT",
      parameters: new object[] {
        Username,
        StatusCode,
      });
}

//StatusCode now contains the status code from the [spIfUserExists].
Console.WriteLine(Convert.ToInt32(StatusCode.Value));

The output parameters don't require the positional arguments like normal arguments do, e.g., Username. Therefore, you don't need to pass @p[n] to the OUTPUT arguments but only providing them to the parameters list.

There is no difference in coding if you're to use ExecuteSqlRaw. You're only required to remove the await keyword to run ExecuteSqlRaw synchronously.

You can have more than one output parameter in your stored procedure with different datatypes. You only need to follow the same pattern.

2

I know this is really old but I have some stored procedures that use the following as the last line in the proc.

select SCOPE_IDENTITY()

With that said I borrowed EF Core source code snippit and adjusted to allow for ExecuteScalar. https://github.com/dotnet/efcore/blob/main/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs

    public static TResult ExecuteScalar<TResult>(this DbContext dbContext, string sql, params object[] parameters)
    {            
        var facadeDependencies = (IRelationalDatabaseFacadeDependencies)((IDatabaseFacadeDependenciesAccessor)dbContext.Database).Dependencies;

        var rawSqlCommand = facadeDependencies.RawSqlCommandBuilder.Build(sql, parameters);
            
        var logger = facadeDependencies.CommandLogger;

        TResult result = (TResult)rawSqlCommand.RelationalCommand
                            .ExecuteScalar(
                                new RelationalCommandParameterObject(
                                    facadeDependencies.RelationalConnection,
                                    rawSqlCommand.ParameterValues,
                                    null,
                                    dbContext,
                                    logger, true));

        return result;
    }
1

To expand on @AlbertK's answer you can add an extension to the DatabaseFacade type to get different types of scalar values returned.

Make sure you are using the Microsoft.Data.SqlClient package rather than System.Data.SqlClient for your SqlParameter arguments otherwise you will receive a runtime exception. https://github.com/dotnet/efcore/issues/16812

public static class DatabaseFacadeExtensions
{
    public static async Task<TResult> ExecuteScalarAsync<TResult>(
        this DatabaseFacade database, 
        String commandText, 
        CommandType commandType, 
        params SqlParameter[] parameters)
    {
        TResult result;
        using (var cmd = database.GetDbConnection().CreateCommand())
        {
            cmd.CommandText = commandText;
            cmd.CommandType = commandType;
            if (cmd.Connection.State != System.Data.ConnectionState.Open) cmd.Connection.Open();
            cmd.Parameters.AddRange(parameters);
            result = (TResult)(await cmd.ExecuteScalarAsync());
        }
        return result;
    }
}
1

An alternate way which would not require you to modify your SP: Use the FromSqlRaw extension method of DbSet in order to get results in IQueryable.

public static IQueryable<TResult> RunSp<TResult>(this DbSet<TResult> dbSet, string storedProcedure, DbParameter[] parameters = null) where TResult : class
    {
        var paramNames = string.Empty;
        if (parameters != null)
        {
            paramNames = string.Join(",", parameters.Select(a => a.ParameterName));
        }
        return dbSet.FromSqlRaw($"EXEC {storedProcedure} {paramNames}", parameters ?? new object[]{} );
    }

You need to define a DbSet in your context with the result type you want to get:

[Keyless]
    public class TestSpRecord
    {
        public int Field1 { get; set; }
        public string Field2 { get; set; }
    }

Usage would be like:

var resultList = testCtx.TestSpRecords.RunSp("EchoParams", new DbParameter[] {  new SqlParameter("@Param1",10),new SqlParameter("@Param2","text")});
        
0

I usually use this conventional method to get a single integer value from sp.

var commandText=  "EXEC Production.Select_TicketQuantity"+string.format(" @p0={0}, @p1={1}", ticket, reference)

using (var command = dbContext.Database.GetDbConnection().CreateCommand())
                {
                    command.CommandText = commandText;
                    dbContext.Database.OpenConnection();
                    using (var result = command.ExecuteReader())
                    {
                        if (result.HasRows == true)
                        {
                            if (result.Read())
                            {
                                var returnInteger = result.IsDBNull(0) ? 0 : result.GetInt32(0);
                                result.Close();
                                return returnInteger;
                            }

                        }

                    }
                    return 1;
                }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.