2014-04-24 63 views
0

我有以下表test更新表使用情況下,當

Id  Code  ParentId 
1  R   O 
2  Y   O 
3  P   O 
4  O   NULL 

我需要更新test這樣的:

Id  Code  ParentId 
    1  R   4 
    2  Y   4 
    3  P   4 
    4  O   NULL 

我試過,但它不工作,任何想法?

update [dbo].[test] 
set [ParentId] = 
CASE WHEN [ParentId]='' THEN [Id] 
else select top 1 [Id] from [dbo].[PNL] where ParentId=[Code] 
End 

我拿到表test updated

 Id  Code  ParentId 
     1  R   NULL 
     2  Y   NULL 
     3  P   NULL 
     4  O   NULL 
+1

什麼是'[DBO] [PNL]'表是什麼樣子?你會得到什麼錯誤?如果沒有錯誤,結果數據是什麼? – mjsqu

+1

@mjsqu我更新我的問題 – user3548593

+0

通常'根'記錄沒有父 - 'parentId'的值是'空'。你爲什麼希望它成爲自己的父母?這使得一些查詢非常不安全,因爲這是不尋常的(因此尋找根的普通查詢會導致無限遞歸)。 –

回答

1

隨着更新和刪除它通常是安全的先行先試的選擇:

select t1.*, 
    case when t1.parentid is null then t1.id 
    else (select top 1 t2.Id from #t t2 where t1.ParentId = t2.Code) end as new_parentid 
    from #t t1 

,然後做使用CTE的實際更新:

with x as (
    select t1.*, 
    case when t1.parentid is null then t1.id 
    else (select top 1 t2.Id from #t t2 where t1.ParentId = t2.Code) end as new_parentid 
    from #t t1 
) 
update x 
set parentid = new_parentid 
1

直接的解決方法是:
- 將子查詢中()
- 確保在該子查詢指定[test]

(我不得不猜測ParentID[code]來自[test]。)

update [dbo].[test] 
set [ParentId] = 
CASE WHEN [ParentId]='' THEN [Id] 
else (select top 1 [Id] from [dbo].[PNL] where ParentId=[test].[Code]) 
End 
1

如果我理解正確的話,要求相當簡單:

  • 如果一行沒有ParentId,請保持獨立。
  • 如果一行中有一個ParentId與同一個表中的代碼相匹配,則更新ParentId與匹配行的Id

在這種情況下,一個簡單的INNER JOIN更新應該工作:

UPDATE 
    test 
SET 
    ParentId = PT.Id 
FROM 
    test T 
    -- The INNER JOIN will automatically discard all rows without ParentId 
    INNER JOIN 
    test PT ON 
    (PT.Code = T.ParentId)