愚蠢的问题和答案可能不存在(Gasp!呻吟!Gnash!牙齿!)
我有一个选择:
SELECT * FROM SockDrawer WHERE Color = 'red'
这导致3行,行ID为33896,35901,37903 (还有很多其他结果。)
我想要的是这样的:
DECLARE @ROWID INT --- HOW DO I USE ARRAYS? I'll google but an example would help.
DECLARE @COUNT INT
DECLARE @LIMIT INT
SELECT * FROM SockDrawer WHERE Color = 'red'
--(Returns 3 rows. With 3 RowId's 33896, 35901, 33896)
SET @LIMIT = @@ROWCOUNT
SET @COUNT = 1
WHILE @COUNT < @LIMIT BEGIN
SET @ROWID[0] = (SELECT SockKey From SockDrawer WHERE RowID = 33896)
SET @ROWID[1] = (SELECT SockKey From SockDrawer WHERE RowID = 35901)
SET @ROWID[2] = (SELECT SockKey From SockDrawer WHERE RowID = 33896)
SET @Count = @Count + 1
END
GO
Then I need to:
SET @COUNT = 0
WHILE @COUNT < @LIMIT
BEGIN
DELETE FROM SockDrawer WHERE RowID = @ROWID[@COUNT]
END
GO
诀窍是我永远不会知道我是否要处理1行删除或50。
我是个笨蛋。我可以改变。如果我想。
答案 0 :(得分:1)
如果您不关心每种颜色的袜子,那么:
;WITH x AS
(
SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY Color ORDER BY RowID)
FROM dbo.SockDrawer
)
DELETE x WHERE rn > 1;
如果您关心自己保留哪一个,请相应地调整ORDER BY
。