sql server - What is the fastest way to clear a SQL table? -


i have table 300,000 rows , 30 columns. how can clear out? if drop mytable query, takes long time run. i'm trying following stored procedure make copy of table no data, drop original table, , rename new table original:

use [mydatabase] go set ansi_nulls_on go set quoted_identifier on go alter procedure [dbo].[clearthetable] begin     set nocount on;     select * tempmytable mytable 1 = 0;     drop table mytable     exec sp_rename tempmytable, mytable; end 

this took 7 minutes run. there faster way it? don't need logging, rollback or of nature.

if matters, i'm calling stored procedure c# app. guess write code recreate table scratch after doing drop table, didn't want have recompile app time column added or changed.

thanks!

edit

here's updated stored procedure:

use [mydatabase] go set ansi_nulls_on go set quoted_identifier on go alter procedure [dbo].[clearthetable] begin     set nocount on;     alter database mydatabase     set restricted_user rollback immediate     truncate table mytable     alter database mydatabase     set multi_user end 

best way clear table truncate.

since creating , droping ill assume have no constraints.

truncate table <target table> 

some advantages:

  • less transaction log space used.

the delete statement removes rows 1 @ time , records entry in transaction log each deleted row. truncate table removes data deallocating data pages used store table data , records page deallocations in transaction log.

  • fewer locks typically used.

when delete statement executed using row lock, each row in table locked deletion. truncate table locks table (including schema (sch-m) lock) , page not each row.

  • without exception, 0 pages left in table.

after delete statement executed, table can still contain empty pages. example, empty pages in heap cannot deallocated without @ least exclusive (lck_m_x) table lock. if delete operation not use table lock, table (heap) contain many empty pages. indexes, delete operation can leave empty pages behind, although these pages deallocated background cleanup process.


Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -