如何使用Sql Server 2008从表中删除前1000行?
我在SQL Server中有一个表。 我想从中删除前1000行。 不过,我试过这个,但是我不是只删除前1000行就删除了表中的所有行。
这里是代码:
delete from [mytab] select top 1000 a1,a2,a3 from [mytab]
你试过的代码实际上是两个语句。 一个DELETE
后跟一个SELECT
。
你没有按照什么命令来定义TOP
。
从CTE或类似的表格expression式删除特定的sorting标准是最有效的方法。
;WITH CTE AS ( SELECT TOP 1000 * FROM [mytab] ORDER BY a1 ) DELETE FROM CTE
可能会更好的sql2005 +使用:
DELETE TOP (1000) FROM [MyTab] WHERE YourConditions
对于Sql2000:
DELETE FROM [MyTab] WHERE YourIdField IN ( SELECT TOP 1000 YourIdField FROM [MyTab] WHERE YourConditions )
但
如果要删除特定子集的行而不是任意子集,则应明确指定子查询的顺序:
DELETE FROM [MyTab] WHERE YourIdField IN ( SELECT TOP 1000 YourIdField FROM [MyTab] WHERE YourConditions ORDER BY ExplicitSortOrder )
感谢tp @ gbn提及并要求更加清楚准确的答案。
如下面的链接所定义的,您可以直接删除
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
delete from [mytab] where [mytab].primarykeyid in ( select top 1000 primarykeyid from [mytab] )
它很快。 尝试一下:
DELETE FROM YourTABLE FROM (SELECT TOP XX PK FROM YourTABLE) tbl WHERE YourTABLE.PK = tbl.PK
用表名replaceYourTABLE
, XX
用数字代替,例如1000, pk
是表中主键字段的名称。
SET ROWCOUNT 1000; DELETE FROM [MyTable] WHERE .....