11

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?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
samsam114
  • 987
  • 2
  • 8
  • 20
  • 2
    To whomever marked this as "not a real question" - please read the [SET IDENTITY_INSERT](http://msdn.microsoft.com/en-us/library/ms188059.aspx). – OMG Ponies Jul 30 '10 at 15:40
  • 1
    @OMG Ponies - I did wonder why someone had "not a real question"'d it too :-/ – Rob Jul 30 '10 at 15:41

2 Answers2

27

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();
    }
}
Rob
  • 45,296
  • 24
  • 122
  • 150
3

Well, if it's part of a SqlCommand instance, you just add it to the text:

using(SqlConnection myConnection = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "SET IDENTITY_INSERT dbo.MyTable ON";
    cmd.CommandText += //set the rest of your command here.
}

I question the necessity of this, however. If you're inserting an identity into a table with enough frequency that you're using code, I would recommend a stored procedure to do your insert. You'd then call it basically the same way:

using(SqlConnection myConnectino = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "usp_insert_record_into_my_table [ParamList]";
    cmd.CommandType = SqlCommandType.StoredProcedure;
}
AllenG
  • 8,112
  • 29
  • 40
  • 4
    Aaaaaargh, stored procedures with "usp_" prefixed, my eyes, my eyes, it burrrrrrns! ;) – Rob Jul 30 '10 at 15:43
  • @Rob - yeah, I know, old convention. I actually like it because it's easier to find within the management studio (for me). It serves no other purpose. If you _really_ want, I guess I can change it. Just for you. :P – AllenG Jul 30 '10 at 15:47
  • 2
    Meh - long as it isn't "sp_", see: http://blogs.lessthandot.com/index.php/DataMgmt/DBProgramming/MSSQLServer/don-t-start-your-procedures-with-sp_ – OMG Ponies Jul 30 '10 at 15:58