私は次のようにSQL Server 2008でテーブル#temp
を持っている:レコードにp_id
値が等しい、h_id
値は(100と300を確認してください)に等しくなければならないことに注意してください現在のデータとお互いの一致条件に基づいてフィールドの値を更新するにはどうすればよいですか?
Id p_id h_id ProvincialPID
1 100 A1256 null
2 200 A7865 null
3 300 A5555 null
4 100 A1256 null
5 300 A5555 null
6 400 A7865 null
...
!一方、p_id
の値は等しくないが、h_id
の値が等しいレコードがある(200と400のように)! 、レコードのp_id
は、他のものと一致するが、そのh_id
マッチ少なくとも一つの他のいない場合は、レコードのp_id
は、別のレコードのp_id
、その後ProvincialPID = p_id
、それ以外のマッチングされている場合:私が欲しいもの
があるという事実に基づいてProvincialPID
列を更新することですその後、ProvincialPID = h_id
例:上記のサンプルデータでは、私が見ることになっています:
Id p_id h_id ProvincialPID
1 100 A1256 100
2 200 A7865 A7865
3 300 A5555 300
4 100 A1256 100
5 300 A5555 300
6 400 A7865 A7865
...
次のコードは、私はそれを実行するのに役立っています。しかし、それは非常に遅く、私はより効率的なコードを適用したいと思います。しかし、私はそれをより効率的にする方法を見つけることができませんでした。どんな助け/助言も非常に高く評価されます。
DECLARE @counter INT = 0;
DECLARE @currentPID varchar(50);
DECLARE @currentID varchar(50);
DECLARE @currentHID varchar(50);
WHILE @counter < (select COUNT(*) from #temp)
BEGIN
set @currentID = (select top (1) x.Id from (select top(@counter) * from #temp order by Id desc) x)
set @currentPID = (select top (1) x.p_id from (select top(@counter) * from #temp order by Id desc) x)
set @currentHID = (select top (1) x.h_id from (select top(@counter) * from #temp order by Id desc) x)
if((select COUNT(*) from #temp t where t.Id != @currentID and t.p_id = @currentPID) > 0)
update #temp
set ProvincialPID = @currentPID
where Id = @currentID
else if ((select COUNT(*) from #temp t where t.Id != @currentID and t.p_id != @currentPID and t.h_id = @currentHID) > 0)
update #temp
set ProvincialPID = @currentHID
where Id = @currentID
SET @counter = @counter + 1;
END;