views:

357

answers:

2

I have a store procedure in SQL Server which returns a value:

CREATE PROCEDURE [dbo].[insertProc]
    @value1 INT,
    @value2 INT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO table1(value1,value2) VALUES (@value1,@value2)

    RETURN SCOPE_IDENTITY();
END

I connect to the DB from ASP.NET using SQL Data Source, which is configured like this:

InsertCommand="@insertedId = insertProc"
InsertCommandType="StoredProcedure"

oninserting="sqlDS_Inserting" 
oninserted="sqlDS_Inserted"

<InsertParameters>
    <asp:Parameter Name="value1" />
    <asp:Parameter Name="value2" />
    <asp:Parameter Name="insertedId" DbType="Int32" Direction="ReturnValue" />
</InsertParameters>

What I want to do it to get the returned value. In the body of sqlDS_Inserted procedure I do like this:

this.insertedId = Convert.ToInt32(e.Command.Parameters["insertedId"].Value);

but I get error:

Object cannot be cast from DBNull to other types.

However, when I look at SQL Server Profiler and run the command (adding declaration of @insertedId variable) it works good. What is the problem and how can I get the returned value of stored procedure from ASP.NET?

A: 

Try this:

{ 
    SqlConnection conMyData = default(SqlConnection); 
    SqlCommand cmdInsert = default(SqlCommand); 
    SqlParameter parmReturnValue = default(SqlParameter); 
    long l = 0; 

    conMyData = new SqlConnection(_SQLDBConnString); 
    cmdInsert = new SqlCommand("insEmployee", conMyData); 

    { 
        cmdInsert.CommandType = CommandType.StoredProcedure; 
        parmReturnValue = cmdInsert.Parameters.Add("RETURN_VALUE", SqlDbType.BigInt); 
        parmReturnValue.Direction = ParameterDirection.ReturnValue; 
        cmdInsert.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = strFirstName; 
        cmdInsert.Parameters.Add("@MiddleInitial", SqlDbType.VarChar).Value = strMI; 
        conMyData.Open(); 
        cmdInsert.ExecuteNonQuery(); 
        l = (long)cmdInsert.Parameters("RETURN_VALUE").Value; 
    } 

    return l; 
}
JonH
This way you also do not have to send out an output parameter.
JonH
+2  A: 

I think this statement is your problem.

InsertCommand="@insertedId = insertProc"

You don't need to explicitly assign the return value of the stored procedure to the return value parameter. Just specify the name of the stored procedure.

 InsertCommand = "InsertProc"

Another thing is that you will have to precede the parameter name in your OnInserted event handler with '@'.

this.insertedId = Convert.ToInt32(e.Command.Parameters["@insertedId"].Value);
Phaedrus
Unfortunately you are right! I was trying with and without @insertedId on the beginning (and many other options), with or without @ in OnInserted, but I think I never tried in this configuration. Anyway, thanks. It works now.
Lukasz Lysik