|
|
|
The standard way to delete all the rows in a SQL Server table is a DELETE statement without a WHERE clause: |
However, in most cases you can speed up your code remarkably with the TRUNCATE TABLE command: |
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 ) |
|
|