Skip to content
Advertisement

What’s wrong with this SQL CREATE + INSERT batch?

What is wrong with this SQL statement?

With the resulting error:

Msg 2627, Level 14, State 1, Line 8
Violation of PRIMARY KEY constraint ‘PK__JaretsSc__9C8A5B696CFE9A03’. Cannot insert duplicate key in object ‘dbo.JaretsSchedule’. The duplicate key value is (1).

Advertisement

Answer

The error message is literally telling you what the problem is. You can’t insert the same value more than once for the ScheduleID column, which you have defined as the primary key. Once workaround here would be to just make this column an identity/auto increment column. Then, don’t even include a value for it when inserting. Instead, let SQL Server handle it:

Note also that I explicitly list out the columns, in order, which are the target for the insert. This is also best practice, and avoids a situation later on wher it might not be clear to which columns the data in the VALUES clause corresponds.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement