如何使用Sql Server 2008从表中删除前1000行?

时间:2012-01-21 19:14:28

标签: sql sql-server sql-delete

我在SQL Server中有一个表。我想从中删除前1000行。但是,我尝试了这个,但我不是删除前1000行,而是删除了表中的所有行。

以下是代码:

delete from [mytab] 
select top 1000 
a1,a2,a3
from [mytab]

7 个答案:

答案 0 :(得分:177)

您尝试的代码实际上是两个语句。 DELETE后跟SELECT

您没有按照什么来定义TOP

对于特定的排序标准,从CTE或类似的表格中删除表达式是最有效的方法。

;WITH CTE AS
(
SELECT TOP 1000 *
FROM [mytab]
ORDER BY a1
)
DELETE FROM CTE

答案 1 :(得分:75)

使用sql2005 +可能更好:

DELETE TOP (1000)
FROM [MyTab]
WHERE YourConditions

对于Sql2000:

DELETE FROM [MyTab]
WHERE YourIdField IN 
(
  SELECT TOP 1000 
    YourIdField 
  FROM [MyTab]
  WHERE YourConditions
)

<强> BUT

如果要删除特定行的子集而不是任意子集,则应明确指定子查询的顺序:

DELETE FROM [MyTab]
WHERE YourIdField IN 
(
  SELECT TOP 1000 
    YourIdField 
  FROM [MyTab]
  WHERE YourConditions
  ORDER BY ExplicitSortOrder
)

感谢tp @gbn提及并要求更清晰准确的答案。

答案 2 :(得分:24)

如下面链接中所定义,您可以直接删除

USE AdventureWorks2008R2;
GO
DELETE TOP (20) 
FROM Purchasing.PurchaseOrderDetail
WHERE DueDate < '20020701';
GO

http://technet.microsoft.com/en-us/library/ms175486(v=sql.105).aspx

答案 3 :(得分:6)

delete from [mytab]
where [mytab].primarykeyid in
(
select top 1000 primarykeyid
from [mytab]
)

答案 4 :(得分:2)

很快。试试吧:

DELETE FROM YourTABLE
FROM (SELECT TOP XX PK FROM YourTABLE) tbl
WHERE YourTABLE.PK = tbl.PK

用表名替换YourTABLEXX一个数字,例如1000, pk是表格主键字段的名称。

答案 5 :(得分:1)

SET ROWCOUNT 1000;

DELETE FROM [MyTable] WHERE .....

答案 6 :(得分:0)

我同意 Hamed elahi Glorfindel

我的添加建议是您可以使用别名删除和更新

/* 
  given a table bi_customer_actions
  with a field bca_delete_flag of tinyint or bit
    and a field bca_add_date of datetime

  note: the *if 1=1* structure allows me to fold them and turn them on and off
 */
declare
        @Nrows int = 1000

if 1=1 /* testing the inner select */
begin
  select top (@Nrows) * 
    from bi_customer_actions
    where bca_delete_flag = 1
    order by bca_add_date
end

if 1=1 /* delete or update or select */
begin
  --select bca.*
  --update bca  set bca_delete_flag = 0
  delete bca
    from (
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    ) as bca
end