C#与mssql,身份错误

时间:2016-03-18 12:11:29

标签: c# sql-server exception

设置Identity_insert时遇到问题。

SqlCommand AddValueRecord = new SqlCommand($"SET IDENTITY_INSERT {TableName} ON "
                        + $"INSERT INTO " + TableName + $" VALUES ('{row.Field<string>(0)}',{row.Field<double>(1)},'{sqlFormattedDate}')"
                        + $"SET IDENTITY_INSERT {TableName} OFF", cn, tr);
                    AddValueRecord.ExecuteNonQuery();

我只有前任

Additional information: An explicit value for the identity column in table 'Root' can only be specified when a column list is used and IDENTITY_INSERT is ON.

2 个答案:

答案 0 :(得分:1)

执行INSERT时,需要提供缺少的列列表。试试

SqlCommand AddValueRecord = new SqlCommand($"SET IDENTITY_INSERT {TableName} ON "
                        + $"INSERT INTO " + TableName + $" + " (col1, col2, col3) " +VALUES ('{row.Field<string>(0)}',{row.Field<double>(1)},'{sqlFormattedDate}')"
                        + $"SET IDENTITY_INSERT {TableName} OFF", cn, tr);
                    AddValueRecord.ExecuteNonQuery();

答案 1 :(得分:0)

您正在尝试将值插入表格的标识列。

您只是在不指定列的情况下插入值,因此它会尝试将值插入到所有列中。您需要指定列,或者更好地使用带有要插入的值的参数化查询。