简体   繁体   English

如何在C#中的内联SQL语句的插入语句之后返回新创建的ID?

[英]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. 我只是想在插入语句之后返回新创建的ID。 How do I do this? 我该怎么做呢?

Add to your query SELECT SCOPE_IDENTITY() after the insert. 插入后,将其添加到查询SELECT SCOPE_IDENTITY() and call 并打电话

idReturned = cmd.ExecuteScalar();

instead of cmd.ExecuteNonQuery() 而不是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: 然后检查idReturned是否为null,cmd.ExecuteScalar()将为您的更新查询返回null,主键应该是Director对象的参与者,因此您可以执行以下操作:

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. 您应该已经将主键传递给InsertOrUpdateDirector来编写更新查询。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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