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

时间:2013-09-11 23:13:57

标签: c# sql-server tsql

[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;
}

我只是想在insert语句之后返回新创建的ID。我该怎么做?

2 个答案:

答案 0 :(得分:6)

插入后添加到您的查询SELECT SCOPE_IDENTITY()。 并致电

idReturned = cmd.ExecuteScalar();

而不是cmd.ExecuteNonQuery()

然后检查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;
}

您应该已将主键传递到InsertOrUpdateDirector以编写更新查询。

答案 1 :(得分:0)

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