我编写了一个只允许100行具有相同CustomerPK
的存储过程,因此如果我们要插入行101,则需要删除具有相同CustomerPK
的最旧行。
我确信有几种方法可以做到这一点,我不确定哪一种最好。这是程序的代码。
DECLARE
@TokenCount INT;
SELECT
@TokenCount = COUNT(*)
FROM
CustomerAuthTokens
WHERE
CustomerPK = @CustomerPK;
IF @TokenCount > 99
BEGIN
DELETE FROM CustomerAuthTokens
WHERE AuthToken IN (SELECT TOP(@TokenCount - 99) AuthToken
FROM CustomerAuthTokens
WHERE CustomerPK = @CustomerPK
ORDER BY TokenCreateTime ASC);
END
答案 0 :(得分:0)
--Insert your row first
-- This will delete customer rows if there are more than 100 rows for that customer
;WITH cte as
(
SELECT row_number() over (partition by CustomerPK order by TokenCreateTime desc) rn
FROM CustomerAuthTokens
WHERE CustomerPK = @CustomerPK
)
DELETE CTE
WHERE rn > 100