views:

2575

answers:

5

I cannot find an elegant way to get the return value from a stored procedure when using TableAdapters.

It appears the TableAdapter does not support SQL stored procedure return values when using a non-scalar stored procedure call. You'd expect the return value from the auto-generated function would be the return value from the stored procedure but it isn't (it is actually the number of rows affected). Although possible to use 'out' parameters and pass a variable as a ref to the auto generated functions it isn't a very clean solution.

I have seen some ugly hacks on the web to solve this, but no decent solution. Any help would be appreciated.

+1  A: 

The way to get the return value is to use a SqlParameter on the SqlCommand object which has its Direction set to ParameterDirection.ReturnValue. You should check the SelectCommand property of the TableAdapter after calling Fill.

Mike Dimmick
The SelectCommand property is (AFAIK) private to the TableAdapter. I would therefore have to extend each TableAdapter with a partial class which, in my opinion, is not the elegant solution I'm hoping to find.
Chris Driver
A: 

I cannot say for certain because I have do not use TableAdapters, but you might need to look at your stored procedure and include the following around your procedure.

SET ROWCOUNT OFF

BEGIN
<Procedure Content>
END

SET ROWCOUNT ON
Ty
Thanks for the suggestion, but unfortunately SETting the ROWCOUNT doesn't appear to solve my issue.
Chris Driver
+1  A: 

NOTE: The way to go is using a SqlParameter where the Direction = ParameterDirection.ReturnValue

With that said, as someone already mentioned SqlParameters, here is a dynamic method alternate using a DataSet. (if thats how you ride):

Example SQL statement and C# as fallows:

string sql = @"DECLARE @ret int 
            EXEC @ret = SP_DoStuff 'parm1', 'parm2'
            SELECT @ret as ret";

DataSet ds = GetDatasetFromSQL(sql); //your sql to dataset code here...

int resultCode = -1;
int.TryParse(ds.Tables[ds.Tables.Count-1].Rows[0][0].ToString(), out resultCode);

The stored procedure results are loaded into a DataSet and will have as many DataTables as return select statements in the stored procedure.

The last DataTable in the DataSet will have 1 row and 1 column that will contain the stored procedure return value.

sharvell
A: 

Closing this question as it appears return values aren't supported and there is no elegant workaround!

Chris Driver