0

Have a problem with setting up 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();

All i have is ex

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 Answers2

1

You need to provide the missing the column list when you are doing the INSERT. try like

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();
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You are trying to insert a value into the identity column of the table.

You are just inserting values without specifying columns so it will be trying to insert values into all the columns. You need to specify the columns, or better still use a parametrised query with the values you want to insert.

ChrisF
  • 134,786
  • 31
  • 255
  • 325