SQL Data Source - store procedure and return parameter

I have a storage procedure in SQL Server that 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 am connecting to a database from ASP.NET using SQL Data Source, which is configured as follows:

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 to get the return value. In the body of the procedure, sqlDS_InsertedI like it:

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

but I get the error:

Object cannot be cast from DBNull to other types.

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

+3
source share
2 answers

, .

InsertCommand="@insertedId = insertProc"

. .

 InsertCommand = "InsertProc"

, OnInserted '@'.

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

:

{ 
    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; 
} 
0

Source: https://habr.com/ru/post/1721910/


All Articles