开发者

Getting stored procedure's return value with iBatis.NET

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.


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 );
}


You might want to check out the following article http://www.barebonescoder.com/2010/04/ibatis-net-stored-procedures-return-values/ on how to retrieve return values.

I've used it in QueryForObject and Insert scenarios where the last statement is a return statement in the stored procedure.

Pay particular attention to the class attribute on the "parameterMap" element. It's a lot prettier than the answer above and I believe it's more inline with the way IBatis.Net was intended to be used.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜