2017-03-29 2 views
0

このスクリプトで複数のテーブルにあるカラムを更新する際に問題があります。私はこれを使用してUnit Idの重複がDB全体に広がらないようにしたいと考えています。 FOREIGN KEY制約 "のPpt $ {FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}" と競合複数のテーブルにある1つのカラムの値をマージできません

UPDATE文:私は、このエラーメッセージを取得しておきます。競合は データベース "MQS-demo"、テーブル "dbo.Unit"、列 'UnitID'で発生しました。

REFERENCE制約 "の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 
関連する問題