How to put SET IDENTITY_INSERT dbo.myTable ON statement

前端 未结 2 2126
难免孤独
难免孤独 2020-12-17 17:44

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?

2条回答
  •  爱一瞬间的悲伤
    2020-12-17 18:43

    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;
    }
    

提交回复
热议问题