Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

The fastest way to delete all the rows in a table

Total Hit ( 2902)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


The standard way to delete all the rows in a SQL Server table is a DELETE statement without a WHERE clause:

Click here to copy the following block
DELETE FROM MyTable

However, in most cases you can speed up your code remarkably with the TRUNCATE TABLE command:

Click here to copy the following block
TRUNCATE TABLE MyTable

This statement is faster, because it doesn't delete rows one by one; instead, it directly deallocates all the data pages allocated to the table. As with the DELETE statement, TRUNCATE TABLE raises an error if the operation violates the referential integrity rules of the database, and the operation is fully logged, so you can rollback it if it's inside a transaction.
There are two major differences from DELETE that you should keep into account: TRUNCATE TABLE resets the IDENTITY counters and doesn't fire any trigger, if there is one. Keep these differences into account if you replace your DELETE statements with TRUNCATE TABLE. UPDATE: There is also another major difference between DELETE and TRUNCATE TABLE: TRUNCATE TABLE permissions default to the table owner and are not transferable. Also, this permission is typically not granted by a DBA to user accounts. Thanks to Michael D.Long for this clarification. UPDATE: Martin Lanza send us an interesting note on using TRUNCATE. The statistics are not reset, various items in sysindexes are not updated, etc. Under SS65 Martin encountered problems with tables truncated and as a general rule he now always issue a DBCC CHECKTABLE command to fix the problem.



Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.