3
My doubt is the following: I have my cursor for the interaction line by line and within it I have one while
for horizontal interaction. I am trying to popular a table whose PK does not have identity
, using the MAX
and setting the value +1 within the while
, however is crashing error stating that the entered value already exists in the table.
DECLARE @RANGE_DE INT,
@RANGE_ATE INT
declare @MaxId int;
declare @teste int;
DECLARE C_REGISTROS CURSOR FOR
SELECT
RANGE_DE,
RANGE_ATE
FROM
#TEMPPARAMETROS
OPEN C_REGISTROS
FETCH NEXT FROM C_REGISTROS INTO @RANGE_DE, @RANGE_ATE
WHILE (@@FETCH_STATUS = 0)
BEGIN
set @teste = (select max(nroproposta) from propadesao);
set @MaxId = (SELECT MAX(IdPropAdesao) FROM PROPADESAO);
while (@RANGE_DE <= @RANGE_ATE)
begin
INSERT INTO
PROPADESAO
(
IdPropAdesao
,IdTpProduto
,IdUnidade
,DtStatus
,IdCorretor
,NroProposta
,StatusAtual
,IdMatDivulga
)
SELECT
@MaxId
,IdTpProduto
,1
,GETDATE()
,IDCORRETOR
,@teste
,CASE
WHEN IDCORRETOR is null THEN 2
WHEN IDCORRETOR IS NOT NULL THEN 3
END
,idcontrato
FROM
#TEMPPARAMETROS
set @range_De += 1
SET @MaxId += 1
set @teste += 1
end
FETCH NEXT FROM C_REGISTROS INTO @RANGE_DE, @RANGE_ATE
END
CLOSE C_REGISTROS
DEALLOCATE C_REGISTROS
Follow the error :
Msg 2627, Level 14, State 1, Line 21 Violation of PRIMARY KEY constraint 'PK_PropAdesao'. Cannot insert duplicate key in object 'dbo.PROPADESAO'. The duplicate key value is (5654054). The statement has been terminated. Msg 2627, Level 14, State 1, Line 21 Violation of PRIMARY KEY constraint 'PK_PropAdesao'. Cannot insert duplicate key in object 'dbo.PROPADESAO'. The duplicate key value is (5654055).
Hello! Welcome to Sopt! Could report complete error?
– Dherik
Oops, thank you, my darling! Follows error : Msg 2627, Level 14, State 1, Line 21 Violation of PRIMARY KEY Constraint 'Pk_propadesao'. Cannot Insert Duplicate key in Object 'dbo.PROPADESAO'. The Duplicate key value is (5654054). The statement has been terminated. Msg 2627, Level 14, State 1, Line 21 Violation of PRIMARY KEY Constraint 'Pk_propadesao'. Cannot Insert Duplicate key in Object 'dbo.PROPADESAO'. The Duplicate key value is (5654055). And this is repeated by all loop interactions.
– AbnoanMuniz
Oops! Edit your question and put the bug there! Add other information that you think is relevant and that can help us.
– Dherik