In a SQL Server 2008 I have a simple stored procedure moving a bunch of records to another table:
CREATE PROCEDURE [dbo].MyProc(@ParamRecDateTime [datetime])
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].Table2
SELECT
...,
...
FROM [dbo].Table1
WHERE RecDateTime <= @ParamRecDateTime
DELETE FROM [dbo].Table1
WHERE RecDateTime <= @ParamRecDateTime
END
Running it from within SQL Server Management Studio, I get the job done and return value = 0
DECLARE @return_value int
EXEC @return_value = dbo.MyProc @ParamRecDateTime = '2011-06-25 11:00:00.000'
SELECT 'Return Value' = @return_value
But when I call the same stored procedure from an app using Entity framework, I also get the job done but the return value is "-1":
int result = myrepository.MyProc(datetimePar);
MessageBox.Show(result.ToString());
I didn't manage to find an explanation for this error, but found this discouraging post, where it's said that there is no standard for this type of return codes in SQL Server.
What is the good, reliable way of getting know of a Stored Procedure execution result when calling it from Entity Framework and when the Stored Procedure doesn't return any entities?
See OUTPUT attribute for SQL param of store procedure, here
One way to do it is to call
ExecuteStoreCommand
, and pass in aSqlParameter
with a direction ofOutput
:Originally I tried using a direction of
ReturnValue
:but
retval.Value
would always be0
. I realized thatretval
was the result of executing theMyProc @dtparm
statement, so I changed it to capture the return value ofMyProc
and return that as an output parameter.For future reference: I had the same issue but needed multiple OUTPUT variables. The solution was a combination of both answers. Below is a complete sample.
Please note the Types used (decimal.) If another type is needed, remember to not only change it in the method argument list but also the
SqlDbType.XXX
.