TOP
without an order by is not deterministic, also when using TOP(n)
, n
must be an outer reference. You can perform your update using CROSS APPLY
, which allows both TOP
and a deterministic order to be used:
UPDATE t
SET SomeID = NULL
FROM @Quantities AS q
CROSS APPLY
( SELECT TOP (q.CountToUpdate) t.ID, t.SomeID, t.Status
FROM dbo.TableName AS t
WHERE t.SomeID = q.SomeID
AND t.Status = 960
ORDER BY t.ID
) AS t;
Full working example:
DECLARE @T TABLE (ID INT IDENTITY, SomeID INT, Status INT);
DECLARE @Q TABLE (SomeID INT, CountToUpdate INT);
INSERT @T (SomeID, Status)
VALUES
(1, 960), (1, 960), (1, 960), (1, 960), (1, 960),
(2, 960), (2, 960), (2, 960), (2, 960), (2, 960),
(3, 960), (3, 960), (3, 960), (3, 960), (3, 960);
INSERT @Q (SomeID, CountToUpdate)
VALUES (1, 4), (2, 3), (3, 2);
UPDATE t
SET SomeID = NULL
FROM @q AS q
CROSS APPLY
( SELECT TOP (q.CountToUpdate) t.ID, t.SomeID, t.Status
FROM @T AS t
WHERE t.SomeID = q.SomeID
AND t.Status = 960
ORDER BY t.ID
) AS t;
SELECT *
FROM @t;