mercredi 27 mai 2015

An INSERT INTO in MSSQL Server 2005 that groups by a column leads to unexpected duplicate key violation

I am executing a stored procedure on Microsoft SQL Server 2005. The code in question has worked flawlessly for about 12 months, but is now failing on "duplicate key violation error"

How is it possible to get a duplicate key violation error with the following?

This is the error:

Violation of Primary Key constraint 'Pk_temp_item_sales_details' Cannot insert duplicate key in object 'dbo.temp_item_sales_details'. [SQLSTATE 23000][Error2627]

This is the SQL that is executed:

TRUNCATE TABLE temp_item_sales_details;

INSERT INTO temp_item_sales_details
            (item_id,
             last_order_date)
SELECT detail.item_no,
       Max(header.sales_invoice_date)
FROM   invoice_header header WITH(NOLOCK)
       JOIN invoice_detail detail WITH(NOLOCK)
         ON header.invoice_number = detail.invoice_no
WHERE  Isnumeric(detail.item_no) = 1
GROUP  BY detail.item_no 

item_no in the invoice_detail table is a varchar whereas the item_id in the temp_item_sales_details table is a numeric, but I am only selecting numeric values with ISNUMERIC(detail.item_no) = 1

Aucun commentaire:

Enregistrer un commentaire