Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
samsam114 Avatar asked Jul 30 '10 15:07

samsam114


2 Answers

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();
    }
}
like image 77
Rob Avatar answered Sep 25 '22 02:09

Rob


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;
}
like image 31
AllenG Avatar answered Sep 25 '22 02:09

AllenG