Home > Database > Mysql Tutorial > How to Retrieve the Inserted ID After an SQL INSERT Command in C# MVC 4?

How to Retrieve the Inserted ID After an SQL INSERT Command in C# MVC 4?

Patricia Arquette
Release: 2025-01-17 01:42:13
Original
500 people have browsed it

Retrieving the Inserted ID After an SQL INSERT in C# MVC 4

How to Retrieve the Inserted ID After an SQL INSERT Command in C# MVC 4?

This article demonstrates how to insert data using C# in an MVC 4 application and retrieve the ID of the newly inserted record. While ExecuteNonQuery indicates the number of rows affected, obtaining the inserted ID requires a different approach.

The most straightforward method utilizes ExecuteScalar. However, the result needs to be explicitly cast to an integer:

<code class="language-csharp">int modified = (int)cmd.ExecuteScalar();</code>
Copy after login

After successful execution, modified will hold the newly generated ID.

For SQL Server 2005 and later, leveraging the OUTPUT keyword within the INSERT statement provides a more efficient solution:

<code class="language-csharp">using (SqlCommand cmd = new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) OUTPUT INSERTED.ID VALUES(@na,@occ)", con))
{
    cmd.Parameters.AddWithValue("@na", Mem_NA);
    cmd.Parameters.AddWithValue("@occ", Mem_Occ);
    con.Open();

    int modified = (int)cmd.ExecuteScalar();

    if (con.State == System.Data.ConnectionState.Open) con.Close();

    return modified;
}</code>
Copy after login

For older SQL Server versions, the SCOPE_IDENTITY() function offers a comparable alternative:

<code class="language-csharp">using (SqlCommand cmd = new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY();", con))
{
    cmd.Parameters.AddWithValue("@na", Mem_NA);
    cmd.Parameters.AddWithValue("@occ", Mem_Occ);
    con.Open();

    int modified = Convert.ToInt32(cmd.ExecuteScalar());

    if (con.State == System.Data.ConnectionState.Open)
        con.Close();

    return modified;
}</code>
Copy after login

These methods ensure you accurately retrieve the ID of the inserted record, regardless of your SQL Server version. Remember to handle potential exceptions appropriately in a production environment.

The above is the detailed content of How to Retrieve the Inserted ID After an SQL INSERT Command in C# MVC 4?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template