I have this little question that's been on my mind for a while now.
Here it goes:
Is it possible to temporary disable the Auto_Increment on the column ID.
So that I can add a new row to the table and being able specify the ID value when inserting the row.
And then in the end enable the Auto_Increment again, and let do its work as usual?
And if its possible how can I do it?
The table structure is very simple
Column name (attributes)
ID (Primary Key, Auto Increment, int, not null)
Name (nvarchar(100), not null)
Note:
People
.I really hope its possible, it would come very handy.
Thanks
EDIT
SqlActions SqlActions = new SqlActions();
SqlCeCommand SqlCmd = new SqlCeCommand("SET IDENTITY_INSERT People ON", SqlActions.Connection());
try
{
SqlCmd.ExecuteNonQuery();
}
catch (SqlCeException Error)
{
Console.WriteLine(Error.ToString());
}
string query = "INSERT INTO People SET (ID, Nome) VALUES (@ID, @Nome)";
SqlCeCommand SqlInsert = new SqlCeCommand(query, SqlActions.Connection());
SqlInsert.Parameters.AddWithValue("@ID", 15);
SqlInsert.Parameters.AddWithValue("@Nome", "Maria");
try
{
SqlInsert.ExecuteNonQuery();
}
catch (SqlCeException Error)
{
Console.WriteLine(Error.ToString());
}
The connection string is working, I have tried it.
He reports:
There was an error parsing the query. [ Token line number = 1,Token line offset = 20,Token in error = SET ]
SOLUTION thanks to OrbMan
SqlActions SqlActions = new SqlActions();
SqlCeCommand SqlCmd = new SqlCeCommand("SET IDENTITY_INSERT People ON", SqlActions.Connection());
try
{
SqlCmd.ExecuteNonQuery();
string query = "INSERT INTO People (ID, Nome) VALUES (@ID, @Nome)";
SqlCmd.CommandText = query;
SqlCmd.Parameters.AddWithValue("@ID", 15);
SqlCmd.Parameters.AddWithValue("@Nome", "Vania");
SqlCmd.ExecuteNonQuery();
}
catch (SqlCeException Error)
{
Console.WriteLine(Error.ToString());
}
I believe you can use SET IDENTITY_INSERT
. I am not sure if this works in all versions.
Update 2:
Try this version:
SqlActions SqlActions = new SqlActions();
SqlCeCommand SqlCmd = new SqlCeCommand("SET IDENTITY_INSERT People ON", SqlActions.Connection());
try
{
SqlCmd.ExecuteNonQuery();
string query = "INSERT INTO People (ID, Nome) VALUES (@ID, @Nome)";
SqlCmd.CommandText = query;
SqlCmd.Parameters.AddWithValue("@ID", 15);
SqlCmd.Parameters.AddWithValue("@Nome", "Maria");
SqlCmd.ExecuteNonQuery();
}
catch (SqlCeException Error)
{
Console.WriteLine(Error.ToString());
}