简体   繁体   English

使用 @@IDENTITY / scope_identity() 时插入 2 行而不是 1 行

[英]2 rows inserted instead of 1 when using @@IDENTITY / scope_identity()

using (SqlConnection connection = new SqlConnection(ConnectionString))
    {
        string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID); SELECT CAST(scope_identity() AS int)";
        SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@FBUID", FBUID);

        connection.Open();
        command.ExecuteNonQuery();

        int lastID = (int)command.ExecuteScalar();

    }

Without the没有

SELECT CAST(scope_identity() AS int)

One row is inserted.插入一行。 But since I need the ID from the created row im using scope_identity.但是因为我需要使用 scope_identity 创建的行中的 ID。 However, when I use this, 2 rows are created instead of one.但是,当我使用它时,会创建 2 行而不是 1 行。

Did I miss something?我错过了什么?

Thanks谢谢

The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery();您发布的代码中的问题是您运行了 2 次相同的查询......一次使用ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();最后一个是(int)command.ExecuteScalar();

If you try to use only the executeScalar i think you have the result's you want....如果你尝试只使用 executeScalar 我认为你有你想要的结果......

Try and hope this helps...尝试并希望这会有所帮助...

If you want you can use Parameter to retrieve the Identity, like they do in this Article如果你愿意,你可以使用参数来检索身份,就像他们在本文中所做的那样

If you would use gbn or my answer from your first question, the problem shouldn't occur.如果您在第一个问题中使用gbn我的回答,则不应该出现问题。

Try doing尝试做

 using (SqlConnection connection = new SqlConnection(ConnectionString))     
    {         
    string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID);";         
    SqlCommand command = new SqlCommand(query, connection);            
    command.Parameters.AddWithValue("@FBUID", FBUID);         
     connection.Open();         
    command.ExecuteNonQuery();
     query = "SELECT CAST(scope_identity() AS int)";     
     command = new SqlCommand(query, connection);                   
    int lastID = (int)command.ExecuteScalar();      
    } 

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

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