1

我编写了一个存储过程,它只允许有 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
4

1 回答 1

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
于 2013-07-10T19:19:48.253 回答