Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT statement runs correctly but throws a 'violation of PK contstraint' error?

I am inserting the first product in the Products table. My answer statement works correctly, but I get a violation of primary key constraint:

Cannot insert duplicate key in object. The duplicate key value is [...].

The record inserts correctly, but it also inserts a "0" record above the record I inserted. Not sure what is going on.

I can't see where my insert statement is wrong, I based it on an insert statement from sqlservertutorial.net. I don't know what is wrong.

INSERT INTO products (code, P_Name, p_line, P_Collection, P_Colour,
                      P_Size, P_Price, active)
VALUES ('17881832980551', 'Austin Record', 'T-Shirt', 'Classic', 'Athletic Heather',
        'S', '39.50', 'Y');

The Code column in my Products table is the primary key.

The records is getting inserted correctly, as expected, but I also get an extra "0" record inserted, as well as the following error message:

(2 rows affected)

Msg 2627, Level 14, State 1, Line 3
Violation of PRIMARY KEY constraint 'PK__Products__A25C5AA60C388384'. Cannot insert duplicate key in object 'dbo.Products'. The duplicate key value is (17881832980551)

like image 677
Eric Leclerc Avatar asked Dec 08 '25 06:12

Eric Leclerc


1 Answers

try this

IF Not EXISTS(SELECT TOP 1 * FROM products WHERE code = '17881832980551')
BEGIN
     INSERT INTO products (code, P_Name, p_line, P_Collection, P_Colour,
                      P_Size, P_Price, active)
      VALUES ('17881832980551', 'Austin Record', 'T-Shirt', 'Classic', 'Athletic Heather',
        'S', '39.50', 'Y');
END
ELSE
BEGIN
     SELECT 'Record already added'
END
like image 64
asmgx Avatar answered Dec 09 '25 18:12

asmgx