2013-03-28 4 views
1

"우연히"(힘든 아침 이었으므로) 기본 키가있는 테이블에서 행을 삭제하면 이전 레코드와 함께 다시 삽입 할 수 있습니다 키, 테이블이 자동으로 기본 키를 증가시키는 경우에도?기본 키가있는 테이블에서 우발적으로 삭제 된 행

+2

네, 그것은 가능 . 시도해 보았 니? – Jocelyn

+0

사용자 중 한 명이 실수로 실수를 범했습니다. 이제는 유효성 검사를 통해 수정했습니다. 하지만 프로덕션 환경에 있기 때문에 필자가 그 행에 pk를 설정할 수 있다는 것을 확실히 알기 전까지 삽입을 시도하고 싶지 않았습니다. –

답변

1

또는 REPLACE 문에 제공되지 않는 경우 AUTO_INCREMENT 기능은 값을 할당합니다. 그렇지 않으면 값을 제공하고 기존 키와 충돌하지 않으면 그대로 사용합니다.

+0

확인 +1 감사합니다! –

2

TSQL 저는 정말 이상한 환경을 가지고 있습니다. 어떤면에서는 매우 제한되어 있고, 다른면에서는 슬프게도 열려 있습니다. 이미 사용 PK 값의 삽입을 허용하지 않습니다, mainTable하는 protoTable을 ... 전체 테이블을 다시

/**** 
create protoTable w/ same structure as your mainTable that has the data you are trying to fix in this example the fieldname of the primary key is FldPK 
assumption here is that your primary key is getting auto incremented 
get a list of the fields in the mainTable that are NOT NULL. 
in this example those fields are <not null fields> 
get a list of all fields in the mainTable 
in this example <all fields>, rather than spell out the fields. DO NOT INCLUDE the primary key field name 
***/ 
declare @x int, @y int, @iLast int 
select @iLast = (select MAX(FldPK) from mainTable) 
set @x = 1 
while @x <= @iLast 
begin 
    select @y = (select COUNT(*) from mainTable where FldPK = @x) 
    if @y = 1 
    begin 
     insert into protoTable(<all fields>) 
     select <all fields> from mainTable where FldPK = @x 
    end 
    else 
    begin 
     insert into protoTable (<not null fields>)values('N','xyz'+convert(varchar,@x)) /*or whatever values are valid to fulfill not null*/ 
     /* this is where you keep one or more of the missing rows to update later with the lost data */ 
     if @x <> 126 
     begin 
      delete protoTable where FldPK = @x 
     end 
    end 
    set @[email protected]+1 
end 

그런 다음 백업에 mainTable 이름을 변경하고 이름을 변경했다

HTH가

관련 문제