Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

delete from all tables

Status
Not open for further replies.
Nov 29, 2002
64
US
hello everyone, is it there a SQL query that will empty all the tables in my database? Something like DELETE FROM ALL_TABLES...

Thanks!
alfredo
 
Check out FAQ183-4107. The undocumented stored procedure sp_MSforeachtable might be what you want.

-SQLBill
 
Thanks SQLBill, your tip really helped!
I've created the following procedure to clean up my tables:
Code:
IF (OBJECT_ID ('dbo.DeleteRecordsAllTables') IS NOT NULL)
	DROP PROCEDURE dbo.DeleteRecordsAllTables
GO
CREATE PROCEDURE dbo.DeleteRecordsAllTables AS
BEGIN
	SET NOCOUNT ON

	-- Declare a cursor that gets a list of all the
        -- tables in the database
	
	DECLARE tablesList CURSOR FOR
		SELECT table_name FROM information_schema.tables
			WHERE table_type = 'BASE TABLE'
			ORDER BY table_name

	-- Scratch variables used in the program
	DECLARE @lcTableName VARCHAR(100)
	DECLARE @sqlString NVARCHAR(1000)

	-- Output table that contains all the results
	CREATE TABLE #tableStodelete (tableName VARCHAR(100))
	
	-- Open the cursor and loop through it
	OPEN tablesList
	FETCH NEXT FROM tablesList INTO @lcTableName
	WHILE (@@FETCH_STATUS = 0)
	BEGIN
		-- From the command to execute against each table and execute
		-- the same
		SET @sqlString = 'DELETE FROM ' + @lcTableName
		EXEC sp_executesql @sqlString

		
	END
	-- Cleanup the cursor
	CLOSE tablesList
	DEALLOCATE tablesList

END
GO

EXEC dbo.DeleteRecordsAllTables
And it seems to be working just fine. However it takes a long time to clean up the 3 tables I created in a sample database. Any suggestions to make it faster?
cheers,
alfredo
 
Alfredo,
Use the sp_MSForEachTable command.
Code:
exec sp_MSForEachTable 'truncate table ?'


Denny

--Anything is possible. All it takes is a little research. (Me)
 
you're right... [hammer] ... thanks!!

Code:
EXEC sp_MSforeachtable @command1 = 'DELETE FROM ?'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top