Return ID on INSERT?

后端 未结 5 912
灰色年华
灰色年华 2020-12-03 13:10

I have an INSERT query and I want the DB to return the ID of the row I just inserted.

sqlString = \"INSERT INTO MagicBoxes (OwnerID, Key, Name, Permissions,          


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-03 14:07

    You just need to add @ID to the params collection and then retrieve it like this,

    cmd.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
    cmd.ExecuteNonQuery();
    //Now just read the value of: cmd.Parameters["@ID"].value
    

    Or, if you prefer this syntax:

    SqlParameter param = new SqlParameter("@ID", SqlDbType.Int, 4);
    param.Direction = ParameterDirection.Output;
    cmd.Parameters.Add(param);
    

提交回复
热议问题