做这种事情的最常见方法(我知道)是使用自联接:
-- WARNING: Untested Code
UPDATE YourTable
SET Origin.Description = Proxy.Description
FROM YourTable Origin
JOIN YourTable Proxy
ON Origin.Id = Proxy.Id - 1
WHERE Origin.Description IS NULL
AND Proxy.Description IS NOT NULL
这将连接YourTable
到自身,因此一行看起来像这样:
Origin.Id | Origin.Description | Proxy.Id | Proxy.Description
------------------------------------------------------------------
5 | NULL | 4 | This is a description
编辑
如果您不能保证总是递增 ID,那么您将要使用ROW_NUMBER
:
;WITH NumberedRows
AS
(
SELECT *
, ROW_NUMBER() OVER(ORDER BY Id) AS [Row #]
FROM YourTable
)
SELECT *
FROM NumberedRows Origin
JOIN NumberedRows Proxy
ON Origin.Id = Proxy.Id - 1
WHERE Origin.Description IS NULL
AND Proxy.Description IS NOT NULL