删除条目,如果超过50

时间:2019-12-02 12:05:55

标签: sql sql-server transactions

例如,我可以在同一台计算机上有75个条目,在这种情况下:clt98079

,我想删除最后的条目(如果超过50个(按日期,最旧的条目),并保留最新的50个条目)。如何完成交易?我正在按列检查PC Hostname,并按旧条目检查列CheckDate

begin tran
    if  (Select Count(*) FROM dbo.Clients WHERE Hostname='clt98079') > 50
    begin
        delete from dbo.Clients where ID in (
            select dbo.Clients.CheckDate from dbo.Clients
            /////not sure how to finish the last bit here/////
        )
    end

1 个答案:

答案 0 :(得分:3)

您的语法类似于SQL Server,它为您提供了可更新的CTE选项:

with todelete as (
      select c.*,
             row_number() over (partition by hostname order by checkdate desc) as seqnum
      from dbo.Clients c
      where hostname = 'clt98079'
     )
delete from todelete
    where seqnum > 50;

请注意,您可以删除where子句以保留所有主机名的最新50。