Hello,This is driving me crazy. I have a SQL table that keeps track of various "object" statistics (by statistic type and date). However, when the stored procedure that updates the table is executed, we receive random failures due to the following error:Error Message:Violation of PRIMARY KEY constraint 'PK_stats'. Cannot insert duplicate key in object 'stats'.Below are the environment, table and stored procedure details:Environment:SQL 2000Table:CREATE TABLE [dbo].[stats] ( [object_uid] [uniqueidentifier] NOT NULL , [stat_type] [int] NOT NULL , [stat_date] [int] NOT NULL , [stat_count] [int] NOT NULL ) ON [PRIMARY]ALTER TABLE [dbo].[stats] WITH NOCHECK ADD CONSTRAINT [PK_stats] PRIMARY KEY CLUSTERED ( [object_uid], [stat_type], [stat_date] ) WITH FILLFACTOR = 90 ON [PRIMARY]
Stored Procedure:/*** Update statistics for a given object UID, stat type and date ...* stat_date is in the form: YYYYMMDD**/CREATE PROCEDURE sp_stats_update @object_uid UNIQUEIDENTIFIER, @stat_type INT, @stat_date INTASDECLARE @err_code AS INTEGERSET NOCOUNT ONSET @err_code = 0BEGIN TRANSACTION/** If the statistic type/date already exists, increment the counter * otherwise insert a new record ...*/IF ( EXISTS( SELECT * FROM stats WHERE object_uid = @object_uid AND stat_type = @stat_type AND stat_date = @stat_date ) ) BEGIN UPDATE stats SET stat_count = stat_count + 1 WHERE object_uid = @object_uid AND stat_type = @stat_type AND stat_date = @stat_date SET @err_code = @@ERROR ENDELSE BEGIN INSERT stats VALUES ( @object_uid, @stat_type, @stat_date, 1 ) SET @err_code = @@ERROR END/* If ok, commit ... */IF ( @err_code = 0 ) COMMIT TRANSACTIONELSE ROLLBACK TRANSACTIONRETURN
When the above stored procedure is executed, it first checks if a record exists for the given object_uid, stat_type and stat_date. If no record exists, a record is inserted with a stat_count of 1. If the record does exists, the stat_count is simply incremented by 1.So, -- why does SQL Server keep reporting a primary key violation at seemingly random times?? I thought that a TRANSACTION would prevent this from ever happening?Does anyone see something I have missed in the stored procedure that could cause this error to occur?Or... is this a bug with SQL Server 2000??