2010-03-03 48 views
4

我有列的表結構這樣的更新如何選擇在同一個表作爲值的值用於爲每一行

  • [ID]
  • [名稱]
  • [的ParentId ]
  • [ParentName]

父母都包含在同一個表,我想使用如下語句來填充父名稱列:

UPDATE Table 
    SET ParentName = (select Name 
         from Table 
        where Id = ParentId) 

當我這樣做時,所有的ParentNames都設置爲null。思考?

回答

4

這裏還有一個T-SQL語法,你可以使用:

(順便說一句,我同意對非規範化的擔憂克萊圖斯。)

-- create dummy table 
create table test (id int, name varchar(20), 
parentid int, parentname varchar(20)) 

go 

-- add some rows 
insert test values (1, 'parent A', null, null) 
insert test values (2, 'parent B', null, null) 
insert test values (3, 'parent C', null, null) 

insert test values (11, 'child A 1', 1, null) 
insert test values (12, 'child A 2', 1, null) 
insert test values (33, 'child C 1', 3, null) 

go 

-- perform update 
update c set parentname = p.name from test c join test p on c.parentid = p.id 

go 

-- check result 
select * from test 
+0

+1非常好的答案 – 2010-03-03 05:22:16

0

這裏,子查詢返回空值,那麼它就是ParentName

1

這裏指定空是我的工作

UPDATE TABLE 
SET ParentName = b.Name from 
(
    select t.name as name, t.id as id 
    from TABLE t 
) b 
where b.id = parentid 

注意一個解決方案,我不相信它必須是這個醜陋的,我敢肯定,與OMG Ponies發佈的東西非常相似的東西應該工作,但嘗試,因爲我可能無法做到這一點。

5

我會與update from語句去。

UPDATE tb 
SET 
    tb.ParentName = parent.Name 
FROM Table tb 
INNER JOIN Table parent ON parent.Id = tb.ParentId 

這是特定於T-SQL,但它應該工作得很好。

0
UPDATE 
    T 
SET 
    parentname = PT.name 
FROM 
    MyTable T 
    JOIN 
    MyTable PT ON t.parentid = PT.id 

您發生錯誤,因爲您在子查詢中沒有關聯。你每行

select Name from Table where Id = ParentId -- = no rows 

不能使用別名像UPDATE TABLE T ...所以推動加入得到零行,除非「ID =的ParentId」 /關聯到FROM子句(或CTE或派生表)

相關問題