Click here to Skip to main content
15,904,339 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am trying to truncate all the tables of the current database in one shot.Here is the script i wrote ..

SQL
declare @tblname int 
declare tbl_cursor cursor for
select name from sys.tables 
open tbl_cursor
fetch next from tbl_cursor into @tblname
while @@FETCH_STATUS = 0
begin
	truncate table @tblname <-- this is where i get an error
	fetch next from tbl_cursor into @tblname
end 
close tbl_cursor
deallocate tbl_cursor 

I get an error at the truncate statement..Please help me
Posted
Updated 19-Aug-12 21:21pm
v2

If you are using SQL 2005+ then use the following :
SQL
EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'
 
Share this answer
 
Comments
King Fisher 3-May-14 2:47am    
This is a best solution From this List .My 5.
Mehdi Gholam 3-May-14 2:49am    
Thanks!
anurag19289 29-Jul-14 5:46am    
I think this will not work for tables which are being referenced by foreign key
-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

-- delete data in all tables
EXEC sp_MSForEachTable "DELETE FROM ?"

-- enable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

--some of the tables have identity columns we may want to reseed them
EXEC sp_MSforeachtable "DBCC CHECKIDENT ( '?', RESEED, 0)"
 
Share this answer
 
Try this:
SQL
declare @tblname int 
declare tbl_cursor cursor for
select name from sys.tables 
open tbl_cursor
fetch next from tbl_cursor into @tblname
while @@FETCH_STATUS = 0
begin
	EXECUTE ('truncate table '+ @tblname) <-- this is where i get an error
	fetch next from tbl_cursor into @tblname
end 
close tbl_cursor
deallocate tbl_cursor 

In the case of dependency, this won't truncate the table. It'll throw the error at runtime. First truncate all the dependent table and then try this.

--Amit
 
Share this answer
 
v2
Comments
shadyrocks08 20-Aug-12 6:12am    
Thanks, that worked
_Amy 20-Aug-12 6:33am    
Welcome. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900