我正在尝试编写一个更新语句,它将根据同一个表中的其他列更新newTableNo列。
这就是我所拥有的。
childNo | parentNo |TableID |newTableNo
--------+----------+--------+---------+
26 | NULL | 750 | NULL |
27 | NULL | 751 | NULL |
28 | 27 | 752 | NULL |
29 | 27 | 753 | NULL |
30 | 27 | 754 | NULL |
34 | NULL | 800 | NULL |
这是预期的。
childNo | parentNo |TableID |newTableNo
--------+----------+--------+---------+
26 | NULL | 750 | NULL |
27 | NULL | 751 | NULL |
28 | 27 | 752 | 751 |
29 | 27 | 753 | 751 |
30 | 27 | 754 | 751 |
34 | NULL | 800 | NULL |
格式表
答案 0 :(得分:0)
declare @table table (childNo int, parentNo int, TableID int, NewTableNo int)
insert into @table
values
(26,NULL,750,NULL),
(27,NULL,751,NULL),
(28,27,752,NULL),
(29,27,753,NULL),
(30,27,754,NULL),
(34,NULL,800,NULL)
update t2
set t2.newTableNo = t.TableID
from @table t
full join @table t2 on t2.parentNo = t.childNo
select * from @table
您也可以使用inner join
update t
set t.newTableNo = t2.TableID
from @table t
INNER JOIN @table t2 ON t.parentNo = t2.childNo
where t.parentNo is not null
select * from @table
答案 1 :(得分:0)
您可以尝试使用此脚本更新newTableNo列
declare @table table (childNo int, parentNo int, TableID int, NewTableNo int)
insert into @table
values
(26,NULL,750,NULL),
(27,NULL,751,NULL),
(28,27,752,NULL),
(29,27,753,NULL),
(30,27,754,NULL),
(34,NULL,800,NULL)
UPDATE t
SET t.newTableNo = tt.TableID
FROM @table t
INNER JOIN @table tt ON t.parentNo = tt.childNo
WHERE t.parentNo IS NOT NULL
select * from @table
答案 2 :(得分:0)
看起来你想要使用:
UPDATE t1
SET newTableNo = parents.TableID
FROM
t1
INNER JOIN
(SELECT * FROM t1 WHERE parentNo IS null) parents
ON
Parents.childno = t1.parentNo
答案 3 :(得分:0)
更新:
UPDATE mytable SET newTableNo = t2.TableID FROM mytable
LEFT JOIN (SELECT childNo,TableID FROM mytable) t2 ON t2.childNo = parentNo
如果parentNo或TableID更新,那么newTableNo可能会过时。 您可以轻松选择该值,而无需创建实际数据列:
SELECT t1.childNo, t1.parentNo, t1.TableID, t2.TableID AS newTableNo
FROM mytable t1
LEFT JOIN mytable t2 ON t2.childNo = t1.parentNo