如何将SET IDENTITY_INSERT dbo.myTable置于ON语句中

时间:2010-07-30 15:36:19

标签: c# sql-server identity-insert

我需要做的是有SET IDENTITY_INSERT dbo.myTable ON语句,在c#app中使用上述语句的语法是什么?

2 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:3)

好吧,如果它是SqlCommand实例的一部分,您只需将其添加到文本中:

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.
}
然而,我质疑这种必要性。如果您要将一个标识插入到一个频率足以让您使用代码的表中,我建议您使用存储过程来执行插入操作。然后你会基本上以同样的方式调用它:

using(SqlConnection myConnectino = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "usp_insert_record_into_my_table [ParamList]";
    cmd.CommandType = SqlCommandType.StoredProcedure;
}