删除行的存储过程 - SQL Server 2008 R2

时间:2013-07-10 18:59:41

标签: tsql stored-procedures sql-server-2008-r2

我编写了一个只允许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

1 个答案:

答案 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