Hi All I have been using the below sql to insert n number of records into a table(Renoffcyc).I derive n based on subtracting two datetime feilds in a table. For each record inserted into the Renoffcyc table i have to increment the requestid in a table called table_keys.We do this because we have differant web forms which fetch the enxt requestid from this table_keys table.I dont know why but sometimes the SQL works perfect and sometimes i get an error and unable to understand why this might be happeningMsg 2627, Level 14, State 1, Line 42Violation of PRIMARY KEY constraint 'PK__RENOFFCYC__464936E5'. Cannot insert duplicate key in object 'dbo.renoffcyc'.The statement has been terminated.SQLSET NOCOUNT ONGO --declare @reqno int--set @reqno = 231675declare @num_of_times intdeclare @count intdeclare @frequency varchar(10)declare @num_of_times1 int DECLARE @oldrequestid varchar(50),@newrequestid varchar(50)DECLARE db_cursor CURSOR FOR SELECT Requestid from report_request where requestid in (149142)OPEN db_cursor FETCH NEXT FROM db_cursor INTO @oldrequestidWHILE @@FETCH_STATUS = 0 BEGIN --do work here SET @num_of_times = NULLselect @num_of_times=datediff(month, receiveddate,expirationdate) from report_request where requestid in (@oldrequestid) SET @num_of_times1 = @num_of_times+1set @count=0WHILE @count < @num_of_times1 BEGIN update table_keysset key_id = key_id + 1 where table_name = 'adhoc'Select @newrequestid = key_id from table_keys where table_name = 'adhoc' INSERT INTO [UnderWriting].[dbo].[renoffcyc] ([roc_id] ,[roc_ind] ,[fundtype] ,[prodmth] ,[opa_id] ,[hlthplnid] ,[targetdt] ,[actualdt] ,[freqcd] ,[Comments] ,[entereddt] ,[pltfrmind] ,[groupcnt] ,[rptdesc] ,[rptrsrcetxt] ,[tat] ,[mktsgnm] ,[date_available] ,[requestorid] ,[groupname] ,[groupnbr] ,[tool] ,[datarecpdet] ,[HRS] ,[mins] ,[busneed] ,[origrequestid] ) SELECT @newrequestid ,'O' ,RR.fundingtype ,convert(varchar(30),DATEADD (month , @count+1 ,RR.Receiveddate)) ,SR.Assignto ,RR.hlthplnid ,convert(varchar(30),DATEADD (month , @count+1 ,RR.Receiveddate)) ,convert(varchar(30),DATEADD (month , @count+1 ,RR.Receiveddate)) ,RR.defineschedule ,RR.rptcomments ,convert(varchar(30),DATEADD (month , @count+1 ,RR.Receiveddate)) ,SR.pltfmcd ,SR.groupcnt ,SR.rptdesc ,SR.resource ,SR.tat ,mktsg ,convert(varchar(30),DATEADD (month , @count+1 ,RR.Receiveddate)) ,RR.requestor ,RR.CTNAME ,RR.MSGN ,SR.tool ,SR.datarecpdet ,SR.hrs ,SR.mins ,RR.busneed ,@oldrequestid FROM [UnderWriting].[dbo].[REPORT_REQUEST] RR FULL OUTER JOIN SELECTED_REPORT SRON RR.requestid = SR.requestidwhere RR.requestid = @oldrequestidset @count=@count+1 ENDFETCH NEXT FROM db_cursor INTO @oldrequestidEND -- Cursor loopCLOSE db_cursorDEALLOCATE db_cursor
ExampleI feed a requestid and i know that there will be 13 records that need to be inserted into the renoffcyc table.when i run the query i see that the requestid is incremented 13 times in the table_keys table but it failed with the above errorNeed help on this pleasethanks