如何删除内部连接的顶部(N)行?

时间:2014-02-26 20:52:01

标签: sql-server tsql

我正在尝试使用以下查询从两个表中删除几行

Delete top(3) ss 
from stage.SubmitItemData ss 
INNER JOIN stage.SubmitItems s (NOLOCK) on ss.SubmitItemId = s.SubmitItemId 
where s.AgencyCode = 'NC0860000' and s.StatusId = 8

我感到困惑的是,如果删除参数s.AgencyCodes.StatusId,则查询执行时没有问题。但是,如果我添加这些参数,我会得到(0) rows affected.

我所要做的就是控制在任何给定时间删除的记录数。 top(n)不是最好的方法,因为它看起来好像需要订购才能工作?为这种类型的删除创建一个循环会更好吗?

感谢您的任何建议。

3 个答案:

答案 0 :(得分:4)

DELETE TOP (3)
FROM stage.SubmitItemData
WHERE 
      EXISTS (SELECT 1
              FROM stage.SubmitItems
              WHERE SubmitItemId = SubmitItemData.SubmitItemId
              AND AgencyCode = 'NC0860000'
              AND StatusId = 8)

或者你可以这样做......

DELETE TOP(3) FROM ss 
FROM stage.SubmitItemData ss 
INNER JOIN stage.SubmitItems s WITH (NOLOCK) 
ON ss.SubmitItemId = s.SubmitItemId 
where s.AgencyCode = 'NC0860000' and s.StatusId = 8

答案 1 :(得分:1)

;WITH cte
AS
(
    select *, Row_number() over (order by s.SubmitItemId) As Rno
    from stage.SubmitItemData ss 
    INNER JOIN stage.SubmitItems s (NOLOCK) on ss.SubmitItemId = s.SubmitItemId 
    where s.AgencyCode = 'NC0860000' and s.StatusId = 8
)
DELETE FROM cte where Rno <=3

答案 2 :(得分:0)

尝试这个

DELETE FROM stage.SubmitItemData
WHERE SubmitItemId IN
(SELECT TOP 3 SubmitItemId  
from stage.SubmitItemData ss 
INNER JOIN stage.SubmitItems s (NOLOCK) on ss.SubmitItemId = s.SubmitItemId 
and s.AgencyCode = 'NC0860000'
and s.StatusId = 8
order by ASC);