How do I use Dapper to get the return value of stored proc? How do I use Dapper to get the return value of stored proc? sql-server sql-server

How do I use Dapper to get the return value of stored proc?


You can declare dynamic params with direction: ReturnValueYou can also use "select" instead of "return" and use Query<T> extension.

create procedure sp_foo    as    begin        return 99    end[Test]public void TestStoredProcedure(){    using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))    {        var p = new DynamicParameters();        p.Add("@foo", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);        conn.Execute("sp_foo", p, commandType: CommandType.StoredProcedure);        var b = p.Get<int>("@foo");        Assert.That(b, Is.EqualTo(99));    }}


you'll have to define a SqlParameter for your stored procedure with a Direction.ReturnValue


csharp/server side

var result = conn.QuerySingle<int>(                "sp_test",                new                {                    param1 = "something"                },                commandType: CommandType.StoredProcedure            );

and the stored procedure

create procedure sp_test(varchar(255) param1)    as    begin        if param1 = "bla bla" then -- or some other validation against param1           select -1;        end if;        -- do something        select 1; -- if reached this point everything is fine    end

Approved solution didn't work for me using mysql 5.7.1. So i'm just posting my solution here. result will be 1 for the example and and -1 if param1 is changed to something