JJ.
JJ.

Reputation: 9960

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?

Upvotes: 0

Views: 353

Answers (2)

user2561316
user2561316

Reputation: 404

 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();

Upvotes: 0

Brian Ogden
Brian Ogden

Reputation: 19232

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.

Upvotes: 6

Related Questions