我需要通过自我联接来程序化地更新表。使用SQL Server 2019。
CREATE TABLE Sect
(
Section_Id INT,
Locale VARCHAR(10),
Record_Id INT,
Section_Id_1 INT
);
INSERT INTO Sect (Section_Id, Locale, Record_Id, Section_Id_1)
VALUES
(100, 'US', 1, Null),
(101, 'CA', Null, 100),
(101, 'MD', Null, 100)
目标是用匹配的Record_ID
更新Record_Id
的空值,其中Section_Id_1
等于Section_ID
。
这是预期的结果:
100|US|1|Null
101|CA|1|100
101|MD|1|100
我想我已经接近了:
UPDATE t1
SET Record_Id = t2.Record_Id
FROM Sect t1
INNER JOIN Sect t2 ON t1.Section_Id_1 = t2.Section_Id
WHERE t1.Record_Id IS NULL
感谢大家的帮助。
发布于 2021-07-22 05:05:27
我不熟悉SQL Server 2019。但是我认为你不需要使用INNER JOIN,试试这个。
update
Sect t1
set
Record_Id = (select t2.Record_Id
from Sect t2
where t2.Section_ID = t1.Section_Id_1
and t2.Record_Id is not null
limit 1)
where Record_Id is null
and Section_Id_1 is not null
https://stackoverflow.com/questions/68479174
复制相似问题