I'm trying to adopt this solution to remove duplicate rows from a database table. However, in my case, whether two rows are considered "duplicates", another table must be checked. A full repro for my scenario would be like this:
-- Foreign key between these tables as well as "Group" table omitted for simplicity...
DECLARE @ItemType TABLE(Id INT, Title NVARCHAR(50), GroupId INT);
DECLARE @Item TABLE(Id INT IDENTITY(1,1), ItemTypeId INT, Created DATETIME2);
INSERT INTO @ItemType (Id, Title, GroupId)
VALUES (1, 'apple', 1), (2, 'banana', 1), (3, 'beans', 2);
INSERT INTO @Item (ItemTypeId, Created)
VALUES (1, '20141201'), (2, '20140615'), (3, '20140614');
-- Note: Id's are generated automatically
WITH cte AS (
SELECT ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY Created) AS Rnk
FROM @Item AS i
JOIN @ItemType AS it ON i.ItemTypeId = it.Id
)
DELETE FROM cte
WHERE Rnk > 1;
This fails, obviously, with the following message:
View or function 'cte' is not updatable because the modification affects multiple base tables.
Can this be solved while sticking with the elegant cte-solution? Or does this require a move over to a version based on DELETE
or even MERGE INTO
?