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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With