Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve stored procedure return value with Dapper

I have a stored procedure of this form:

CREATE PROCEDURE AddProduct
    (@ProductID varchar(10),
     @Name  nvarchar(150)
    )
AS
    SET NOCOUNT ON;

    IF EXISTS (SELECT TOP 1 ProductID FROM Products 
               WHERE ProductID = @ProductID)
        RETURN -11
    ELSE
    BEGIN
        INSERT INTO Products ([AgentID], [Name])
        VALUES (@AgentID, @Name)

        RETURN @@ERROR
    END

I have this C# to call the stored procedure, but I can't seem to get a correct value form it:

var returnCode = cn.Query(
    sql: "AddProduct",
    param: new { @ProductID = prodId, @Name = name },
    commandType: CommandType.StoredProcedure);

How can I ensure that the returnCode variable will contain the value returned from either the RETURN -11 or the RETURN @@ERROR lines?

like image 363
Matt W Avatar asked Sep 15 '25 19:09

Matt W


2 Answers

To enable use of the RETURN statement in SQL the C# becomes...

var _params = new DynamicParameters{ @ProductID = prodId, @Name = name };
_params.Add(
    name: "@RetVal",
    dbType: DbType.Int32,
    direction: ParameterDirection.ReturnValue
    );
var returnCode = cn.Execute(
    sql: "AddProduct",
    param: _params,
    commandType: CommandType.StoredProcedure);
return _params.Get<int>("@RetVal");

It's not the implementation I was hoping for, but it works.

like image 72
Matt W Avatar answered Sep 18 '25 08:09

Matt W


I suggest you use SELECT to return the values from your stored procedure. Also you should specify a return type on the dapper call:

RETURN -11

becomes

SELECT -11

and the dapper call becomes:

var returnCode = cn.Query<int>(..

I have implemented this pattern several times and it works as expected.

like image 38
Andy Sinclair Avatar answered Sep 18 '25 09:09

Andy Sinclair