简体   繁体   中英

How do I return the newly created ID after an insert statement from an inline SQL statement in C#?

[HttpPost]
public void InsertOrUpdateDirector(Director director)
{
    int idReturned = 0;

    string query = null;
    myConnection.Open();
    if (director.Operation == 'I')
    {
      query = "INSERT...";
    }
    else if (director.Operation == 'U')
    {
      query = "UPDATE ...";
    }
    var cmd = new SqlCommand(query, myConnection);
    cmd.ExecuteNonQuery();
    myConnection.Close();

    idReturned = "???";

    return idReturned;
}

I'm simply trying to return the newly created ID after the insert statement. How do I do this?

Add to your query SELECT SCOPE_IDENTITY() after the insert. and call

idReturned = cmd.ExecuteScalar();

instead of cmd.ExecuteNonQuery()

Then check to see if idReturned is null, cmd.ExecuteScalar() will return null for your update query, the primary key should be party of the Director object so you can do:

if(idReturned == null){
    return director.DirectorId //just guessing at name of id property here for example sake
}else{
    return idReturned;
}

You should already have the primary key passed into InsertOrUpdateDirector to write the update query.

 Try this code,I hope this will work
myConnection.Open();
    if (director.Operation == 'I')
        {
          query = "INSERT...";
    string query1="select  createdId  from table";

        }
    var cmd = new SqlCommand(query, myConnection);
    Sqlcommand cmd1=new SqlCommand(query1,myConnection);
        cmd.ExecuteNonQuery();
    int CreatedId=cmd1.ExecuteScalar();
    return  CreatedId;
        myConnection.Close();
     myConnection.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM