1
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. However, when I use this, 2 rows are created instead of one.

Did I miss something?

Thanks

Alireza Maddah
  • 5,718
  • 2
  • 21
  • 25
Johan
  • 203
  • 1
  • 2
  • 4

3 Answers3

4

The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();

If you try to use only the executeScalar i think you have the result's you want....

Try and hope this helps...

If you want you can use Parameter to retrieve the Identity, like they do in this Article

2GDev
  • 2,478
  • 1
  • 20
  • 32
0

If you would use gbn or my answer from your first question, the problem shouldn't occur.

Community
  • 1
  • 1
Oliver
  • 43,366
  • 8
  • 94
  • 151
0

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();      
    } 
FIre Panda
  • 6,537
  • 2
  • 25
  • 38