SQL Insert命令抛出错误

时间:2017-07-06 08:16:28

标签: c# sql

 System.Data.SqlClient.SqlException occurred   HResult=0x80131904   Message=Cannot insert explicit value for identity column in table 'DriversDetailsTable' when IDENTITY_INSERT is set to OFF.   Source=.Net SqlClient Data Provider   StackTrace: <Cannot evaluate the exception stack trace>

我在运行代码时遇到上述错误,不知道为什么。这是我的代码:

SqlConnection conn = new SqlConnection(@"Data Source = ComputerName\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;");
        conn.Open();

        SqlDataAdapter adapter = new SqlDataAdapter();

        SqlCommand command = new SqlCommand($@"INSERT INTO DriversDetailsTable (name, Id, DateJoined) VALUES ('Driver4', 1, '2017-07-06')", conn);
        command.ExecuteNonQuery();

        conn.Close();

3 个答案:

答案 0 :(得分:3)

是的,这是因为您的Id列是IDENTITY列,因此您应该在INSERT语句中省略它,如下所示。由于它是一个IDENTITY列,因此您无法为其明确插入值,除非您将IDENTITY_INSERT设置为OFF但不认为您不想这样做

INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06')

SideNote:当您使用硬编码/静态值时,没有看到字符串插值$@"INSERT的C#6语法的原因

答案 1 :(得分:2)

据推测,IdIDENTITY列。因此,您不应尝试INSERT进入Id列 - 从INSERT语句中省略它,并让数据库告诉什么号码已分配:

SqlCommand command = new SqlCommand($@"
INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06');
SELECT SCOPE_IDENTITY();", conn);

并使用ExecuteScalar()来获取值:

int id = (id)(decimal)command.ExecuteScalar();

(有关演员的解释,请参阅Why does select SCOPE_IDENTITY() return a decimal instead of an integer?

其他选择:

  • 使其不是IDENTITY
  • 如果您需要特定值(在大多数情况下不推荐),请暂时禁用此操作期间的身份插入

答案 2 :(得分:0)

如果您确实希望能够出于某种原因插入ID,则需要将IDENTITY_INSERT设置为ON,如下所示:

Set Identity_Insert DriverDetailsTable ON;

这可以针对特定命令执行,如下所示:

SqlCommand command = new SqlCommand($@"
Set Identity_Insert DriverDetailsTable ON;
INSERT INTO DriversDetailsTable (name, Id, DateJoined) VALUES ('Driver4', 1, '2017-07-06');
Set Identity_Insert DriverDetailsTable OFF;", conn);