Violation of PRIMARY KEY constraint error SQL

2020-04-14 10:02发布

问题:

Here is the code

BEGIN TRANSACTION

INSERT INTO [cresql].[dbo].[AR_Transactions] 
       (DateTime , Dirty, Store_ID, Trans_Type,  Cashier_ID, CustNum, Trans_Amount, Prev_Cust_Balance) 
    SELECT   
       DATEADD(MINUTE, -30, Getdate()), 1, 1001, 'C', 100199,     
       CustNum, -Acct_Balance, Acct_Balance 
    FROM  
       [cresql].[dbo].[Customer] 
    WHERE 
       Acct_Balance <> 0  

UPDATE [cresql].[dbo].[Customer] 
SET Acct_Balance = -500 
WHERE Acct_Balance <> 0  

COMMIT TRANSACTION

but I am getting this error

Msg 2627, Level 14, State 1, Line 3
Violation of PRIMARY KEY constraint 'pkAR_Transactions'. Cannot insert duplicate key in object 'dbo.AR_Transactions'.
The statement has been terminated.

I am not a pro at SQL...any ideas what I am doing wrong

回答1:

By design, your table [cresql].[dbo].[AR_Transactions] is supposed to hold only one value for the primary key - in your case, this seems to be a combination of columns that make up this PK.

This is not a SQL issue, but seems to be a design concept.

You should find out what combination of keys is making up your primary key - it may be that the design states that you can insert once and update later on for that combination (although I would not consider this to be good design).

EDIT

Since Trans_Id is the PK, and you are not using that column in your insert, it is either being inserted as IDENTITY, as a DEFAULT (brrrrr), or using a TRIGGER.

IDENTITY: Check to see if the IDENTITY specification is screwed up. If so, just reset it. Here is how to How can I reseed an identity column in a T-SQL table variable?

DEFAULT: This is an odd choice, and you may have to ask the one who designed the database, read documentation, or just simply figure it out on your own. In any case, this is a very uncommon choice.

TRIGGER: Find the trigger and read through the code to see what it is doing. Here is how to find a list of triggers What is the most portable way to check whether a trigger exists in SQL Server?

Alternate scenario:

There could be a trigger that inserts into an AUDIT table that may have the problem. Check if the table has any other triggers and see what they do.