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

本文关键字:语句 新创建 返回 创建 ID 插入 SQL | 更新日期: 2023-09-27 18:30:56

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

我只是尝试在插入语句之后返回新创建的 ID。我该怎么做?

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

插入

后添加到查询SELECT SCOPE_IDENTITY()。并致电

idReturned = cmd.ExecuteScalar();

而不是cmd.ExecuteNonQuery()

然后检查idReturn是否为空,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 中以编写更新查询。

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