Search code examples
c#sql-serveridentity-insert

How to put SET IDENTITY_INSERT dbo.myTable ON statement


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?


Solution

  • 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();
        }
    }