views:

659

answers:

3

How can I retrieve the return value of a stored procedure using iBatis.NET? The below code successfully calls the stored procedure, but the QueryForObject<int> call returns 0.

SqlMap

<procedure id="MyProc" parameterMap="MyProcParameters" resultClass="int">
    MyProc
</procedure>

<parameterMap id="MyProcParameters">
    <parameter property="num"/>
</parameterMap>

C# code

public int RunMyProc( string num )
{
    return QueryForObject < int > ( "MyProc", new Hashtable { { "num", num } } );
}

Stored Procedure

create procedure MyProc
    @num nvarchar(512)
as
begin
    return convert(int, @num)
end

FYI, I'm using iBatis 1.6.1.0, .NET 3.5, and SQL Server 2008.

A: 

Stored procedures don't have a return value like functions.
So, I don't think that will work. Try using output parameters instead.

shahkalpesh
Stored procedures can return values in SQL Server.
MikeWyatt
Yes, you are right. I am not sure, if one should use that feature (assuming that callers won't look at return value, if it is a stored procedure).
shahkalpesh
@shahkalpesh, whenever you write code called by someone else, you can't MAKE them use it properly. There is no reason to not use all the features available. I feel it is better to use the return value as an indication of an error, 0=ok, <0 is minor error (validation, etc.), >0 is fatal error (constraint, etc) For the code in this question, an output parameter is best, so an error code could be returned when the string is not a number. Return values have to be a non null integer. Output parameters can be just about any data type.
KM
@KM: I agree with you.
shahkalpesh
A: 

I'm not sure about your application logic, but your procedure would be better like this:

create procedure MyProc
    @num nvarchar(512)
as
begin
    DECLARE @ReturnValue int
    BEGIN TRY
        SET @ReturnValue=convert(int, @num)
    END TRY
    BEGIN CATCH
        SET @ReturnValue=0 --procedures can not return null, so set some default here
    END CATCH
    return @ReturnValue
end
KM
+1  A: 

It's not pretty, but this works:

SqlMap

<statement id="MyProc" parameterClass="string" resultClass="int">
    declare @num int
    exec @num = MyProc #value#
    select @num
</statement>

C# code

public int RunMyProc( string num )
{
    return QueryForObject < int > ( "MyProc", num );
}
MikeWyatt

related questions