How do I execute a table insert command when the ID column is the primary key and set to autoincrement?
I’ve tried the following:
using (SqlConnection conn = new SqlConnection(connstring))
{
SqlCommand identChange = conn.CreateCommand();
identChange.CommandText = "SET IDENTITY_INSERT table1 ON";
conn.Open();
string commtext = @"Insert INTO table1 (ID, Username)
SELECT @ID, @User";
SqlCommand comm = new SqlCommand(commtext, conn);
comm.Parameters.AddWithValue("@ID", -1);
comm.Parameters.AddWithValue("@User", loggedinuser);
identChange.ExecuteNonQuery();
comm.ExecuteNonQuery();
conn.Close();
}
but regardless of what value is put into ID (i’ve tried 0 and -1), it creates a new row with that value under the ID column. As a result, when I try to insert the next row, it gives me an error since now I have two rows with the same ID.
You just don’t have to mention the column if it is a autoincrement column.