How to put SET IDENTITY_INSERT dbo.myTable ON statement

samsam114 picture samsam114 · Jul 30, 2010 · Viewed 20.1k times · Source

What I need to do is have a SET IDENTITY_INSERT dbo.myTable ON statement, what's the syntax of using the above statement in a c# app?

Answer

Rob picture Rob · Jul 30, 2010

It's just the same as any other bit of SQL:

using (var connection = new SqlConnection("Connection String here"))
{
    connection.Open();
    var query = "SET IDENTITY_INSERT dbo.MyTable ON; INSERT INTO dbo.MyTable (IdentityColumn) VALUES (@identityColumnValue); SET IDENTITY_INSERT dbo.MyTable OFF;";
    using (var command = new SqlCommand(query, connection)
    {
        command.Parameters.AddWithValue("@identityColumnValue", 3);
        command.ExecuteNonQuery();
    }
}