2017-03-29 8 views
0

이 스크립트로 여러 테이블에있는 열을 업데이트하는 데 문제가 있습니다. DB를 통해 UnitId가 중복되는 것을 방지하기 위해 이것을 사용하고 싶습니다. 이 오류 메시지가 계속 : 외래 키 제약 "PPT의 $ {FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}"와 충돌여러 테이블에있는 1 열 값을 병합 할 수 없습니다.

UPDATE 문을. 이 충돌은 데이터베이스 "MQS-demo", 테이블 "dbo.Unit", 열 'UnitID'에서 발생했습니다.

참조 제약 "PPT의 $ {FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}"와 충돌 DELETE 문

. 이 충돌은 데이터베이스 "MQS-demo", 테이블 "dbo.Ppt", 열 'UnitID'에서 발생했습니다. 여기

declare @oldUnitID as int=0; 
declare @newUnitID as int=0; 
declare @temp as TABLE 
(
    bincode nvarchar(200), 
    cnt  int 
) 

insert into @temp 
select bincode, Count(*) 
from unit 
group by bincode -- HAVING count(*)=2 

--select * from @temp 

WHILE (SELECT Count(*) from @temp) > 0 BEGIN 

     DECLARE @bincodetodedup as nvarchar(200); 

     select top(1) @bincodetodedup = bcode 
     from @temp; 

     DECLARE @unitstodedup as TABLE 
     (
      unitid int, 
      num int 
    ) 

     insert into @unitstodedup 
     select distinct UnitID, ROW_NUMBER() OVER(ORDER BY unitid) as num 
     from unit 
     where bincode = @bincodetodedup 
     order by unitid 

     WHILE (SELECT Count(*) from @unitstodedup) > 0 BEGIN 
      SELECT TOP(1) @oldUnitID = Unitid 
      from @unitstodedup 
      where num = 1 

      SELECT TOP(1) @newUnitID = Unitid 
      from @unitstodedup 
      where num > 1 

      update Compatibility 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update PriceList 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update Project 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update ProjectNum 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update Rate 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update Resolve 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update Services 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update TrainingDate 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update Form 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      update Ppt 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 

      --update Unit set [email protected] where [email protected] 
      update Manager 
      set UnitID = @newUnitID 
      where UnitID = @oldUnitID 
     END 

     DELETE FROM unit 
     where unitid = @oldUnitID 

     DELETE TOP(1) from @unitstodedup 

     DELETE TOP(1) from @temp 
END 
+0

오류에도 불구하고 코드에 몇 가지 주요 결함이 있습니다. 순서없이 상위 1을 반복해서 선택합니다. 따라서 이제 어떤 행이 반환되거나 삭제되는지 알 수 있습니다. 루프 내부는 unitstodedup 테이블 변수에서 삭제되지 않기 때문에 내부 루프 또한 무한 루프입니다. 내가보기에 가장 큰 문제는이 전체 중첩 루핑 구문을 집합 기반 접근 방식으로 다시 작성하고 루핑을 완전히 잊어 버려야한다는 것입니다. –

+0

감사합니다! 나는 그것이 무한 루프라는 것을 알지 못했다. – user7101339

답변

0

왜 당신은 당신이 지정하는 변수 끝에 삭제하지 않는 쿼리를 무엇입니까?

DELETE from @temp where bcode = @bincodetodedup 
    DELETE from @unitstodedup where num=1 
    DELETE from @unitstodedup where num>1