I am getting the following error:
Violation of PRIMARY KEY constraint 'PK_ss_student_grade'. Cannot insert duplicate key in object 'dbo.ss_student_grade'. The duplicate key value is (301, 1011, 24801, 33).
If I check the table before the insert there are no records with such a primary key.
The insert is done through C# code and I made sure that the code runs only once. even after the error if I check the table I still get no record with such a primary key.
Note: a trigger runs on the insert in the table but it only writes to a log file and does not affect any data in the database
What could confuse SQL into thinking the key already exists?
EDIT: the code calls a procedure that does the following
insert into ss_student_grade(sg_school_code,sg_acad_year,sg_serial_no,sg_student_key,sg_original_grade,sg_grade,sg_school_grade,sg_category_type,sg_operator,sg_datetime)
select pg_school_code, pg_acad_year, et_serial_no, mep_student_key, pg_grade,pg_grade,pg_grade,'Original', SYSTEM_USER, @ExamCreationDate
from #StudentGrades
where not exists (select 1 from ss_student_grade where sg_school_code = pg_school_code and sg_acad_year = pg_acad_year and sg_serial_no = et_serial_no and sg_student_key = mep_student_key)
I am using SQL Server 2008 R2 and Visual Studio 2010 Ultimate
I would look at the temp table #StudentGrades. It most likely contain duplicates of the data that makes up your unique primary key. The where not exists does not protect against this because SQL is set based.
You most likely need to either change the definition of your PK, change the content of the #StudentGrades table or change the select statement to give unique rows.
This could e.g. be using GROUP BY, or ROW_NUMBER() OVER(PARTITION BY column ORDER BY column)
来源:https://stackoverflow.com/questions/16520884/sql-primary-key-constraint-although-record-does-not-exist