简体   繁体   English

使用SQL插入自动递增

[英]Autoincrement with SQL Insert

There were some previous questions like this but I didn't really understand the answers. 以前有一些类似的问题,但我并不真正理解答案。 Here's my query 这是我的查询

using (SqlCommand cmd = new SqlCommand(
    "INSERT INTO Results VALUES(@ResultID, @HasSucceeded, @ScenarioID, @Screenshot)",
    conn))
{
    cmd.Parameters.AddWithValue("@ResultID", Id);
    cmd.Parameters.AddWithValue("@HasSucceeded", HasSucceeded);
    cmd.Parameters.AddWithValue("@ScenarioID", Id);
    cmd.Parameters.AddWithValue("@Screenshot", screenshot);

    cmd.ExecuteNonQuery();
}

Now I am using Id as a placeholder to for @ResultID . 现在,我将Id用作@ResultID的占位符。 What I really want to do is autoincrement @ResultID with this INSERT INTO query. 我真正想做的是使用此INSERT INTO查询autoincrement @ResultID autoincrement How can I do this? 我怎样才能做到这一点?

Make this an IDENTITY column (for example, IDENTITY(1,1)) and let the database manage it. 将其设置为IDENTITY列(例如IDENTITY(1,1)),然后由数据库进行管理。 Trying to manage it from outside is a threading nightmare. 试图从外部进行管理是一场噩梦。 Then it becomes (noting that it is unusually complicated due to using Id for 2 columns, which sound like an error): 然后它变成了(注意,由于将Id用于2列,这异常复杂,听起来像是一个错误):

int newId = 0;

using (SqlCommand cmd = new SqlCommand(
    @"INSERT INTO Results (HasSucceeded, Screenshot)
      VALUES (@HasSucceeded, @Screenshot);
      DECLARE @ResultID int = SCOPE_IDENTITY();
      UPDATE Results SET ScenarioID = @ResultID
                     WHERE ResultID = @ResultID;
      SELECT @ResultID;", conn))
{
    cmd.Parameters.AddWithValue("@HasSucceeded", HasSucceeded);
    cmd.Parameters.AddWithValue("@Screenshot", screenshot);

    newId = (int)cmd.ExecuteScalar();
}

// ...Use newId here...

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

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