2


我有一个父/子表,想将其 PK 和 FK 更新为新值。问题是 oldParent Ids 应该与与旧 Ids 匹配的新 Ids 同步。所以:

我将此数据作为临时表:

OldID |  OldParentID |  NewID | NewParentID
  1         0            10         NULL
  2         0            11         NULL
  3         2            13         NULL
  4         3            14         NULL

我需要更新 NewParentID 如下:

OldID |  OldParentID |  NewID | NewParentID
  1         0            10         0
  2         0            11         0
  3         2            13         11
  4         3            14         13
4

1 回答 1

0
declare @T table
(
  OldID int, 
  OldParentID int, 
  NewID int, 
  NewParentID int
)

insert into @T 
select 1, 0, 10, null union all
select 2, 0, 11, null union all
select 3, 2, 13, null union all
select 4, 3, 14, null

update T1
  set T1.NewParentID = coalesce(T2.NewID, 0)
from @T as T1
  left outer join @T as T2
    on T1.OldParentID = T2.OldID
于 2011-07-09T08:34:13.823 回答