Fetch scope_identity value in C# code from stored procedure in 3 tier architecture

拟墨画扇 提交于 2019-11-28 02:17:45
Niranjan Singh

You need to get value through output parameter, so you must follow these link:
Get output parameter value in ADO.NET
How to use OUTPUT parameter in Stored Procedure

you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.

While adding parameter do as below after adding extra parameter in your method

param.AddParam(SqlDbType.Int, "@c_Id", IdValue, ParameterDirection.Output);

then access the value of your output parameter as below:

object value = cmd.Parameters["@c_Id"].Value;

Source: Getting the identity of the most recently added record Code Snippet:

string query = "AddCategory";
int ID;
string connect = @"Server=.\SQLExpress;Database=Northwind;Trusted_Connection=Yes;";
using (SqlConnection conn = new SqlConnection(connect))
{
  using (SqlCommand cmd = new SqlCommand(query, conn))
  {
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Category", Category.Text);
    cmd.Parameters.Add("@CategoryID", SqlDbType.Int, 0, "CategoryID");
    cmd.Parameters["@CategoryID"].Direction = ParameterDirection.Output;
    conn.Open();
    cmd.ExecuteNonQuery();
    ID = (int)cmd.Parameters["@CategoryID"].Value;
  }
}

procedure...

CREATE PROCEDURE AddCategory
  -- Add the parameters for the stored procedure here
  @Category NVARCHAR(15),
  @CategoryID INT OUTPUT
AS
BEGIN
  SET NOCOUNT ON;

  -- Insert statements for procedure here
  INSERT INTO Categories (CategoryName) VALUES (@Category)
  SET @CategoryID = SCOPE_IDENTITY()
END

Hope the above reference help you more to understand all of this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!