Coding Villa Forum
FAQs
Advertisements

How to delete all data from all tables in the database?

Iram Online 6/28/2012 11:56:04 AM

Hello Friends!

I want to know is there any way to delete all data from all users tables simultaneously? As it is time consuming and tedious task to delete all data manually.Is there any command or query to delete whole data rows from all user tables?

Waiting for your guidance friends


Thanks

Share with Friends

Advertisements

Answer

Mehmood Online 6/29/2012 12:35:38 AM


-- First disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

EXEC sp_MSForEachTable '
IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1
DELETE FROM ?
else
TRUNCATE TABLE ?
'
GO

-- Now enable referential integrity again
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO





You have many other ways.

Iterate each table through cursor and delete from table on the base of some conditions.

----------------------------Cursor approach-----------------

declare @cmd varchar(4000)
declare cmds cursor for
Select
'drop table [' + Table_Name + ']'
From
INFORMATION_SCHEMA.TABLES
Where
Table_Name like 'tableName%'

open cmds
while 1=1
begin
fetch cmds into @cmd
if @@fetch_status != 0 break
exec(@cmd)
end
close local
deallocate local


Share with Friends

Post reply

 

Enter This Code
Captcha
 

Subscribe

Email me when people reply


Subscribe to the