11

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

4

2 回答 2

25

它与任何其他 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();
    }
}
于 2010-07-30T15:40:49.600 回答
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;
}
于 2010-07-30T15:42:59.690 回答