I have a table in SQL Server. I would like to delete the top 1000 rows from it. However, I tried this, but I instead of just deleting the top 1000 rows it deleted all the rows in the table.
Here is the code:
delete from [mytab]
select top 1000
a1,a2,a3
from [mytab]
8条答案
按热度按时间nukf8bse1#
To enhance the accepted answer code, check out mine. The code will start by deleting 1000 rows from the table at a time, and then increase the batch size by 10% after each iteration. This way, the code will delete more rows as the table gets smaller and reduce the number of loops needed. The variable @count will still store the number of rows affected by each delete statement and the loop will stop when it becomes zero.
whitzsjs2#
The code you tried is in fact two statements. A
DELETE
followed by aSELECT
.You don't define
TOP
as ordered by what.For a specific ordering criteria deleting from a CTE or similar table expression is the most efficient way.
pu82cl6c3#
May be better for sql2005+ to use:
For Sql2000:
BUT
If you want to delete specific subset of rows instead of arbitrary subset, you should explicitly specify order to subquery:
Thanks tp @gbn for mentioning and demanding the more clear and exact answer.
pvcm50d14#
As defined in the link below, you can delete in a straight forward manner
http://technet.microsoft.com/en-us/library/ms175486(v=sql.105).aspx
jogvjijk5#
fcg9iug36#
agxfikkp7#
It is fast. Try it:
Replace
YourTABLE
by table name,XX
by a number, for example 1000,pk
is the name of the primary key field of your table.ie3xauqp8#
I agree with the Hamed elahi and Glorfindel.
My suggestion to add is you can delete and update using aliases