Pages

Thursday 12 April 2012

SQL SERVER - DROP,DELETE,TRUNCATE,SELECT all the tables in the Database

Using sp_MSforeachtable stored procedure we can empty all table or delete all data from all the tables in the database. We can do this with a single line of statement to do these entire action.
   
Let's first create a test database and table to test.


USE master
GO
CREATE DATABASE TestDataBase
GO

USE TestDataBase
GO
CREATE TABLE [dbo].[Account]
( [account_number] [varchar](6) NULL,
[branch_name] [varchar](6) NULL,
[balance] [numeric](8, 2) NULL
) ON [PRIMARY]

USE TestDataBase
GO
INSERT INTO [dbo].[Account]([account_number],[branch_name],[balance])
VALUES('ACC001','B00001',123.45)
GO


--To select all records from all tables in the database:

EXEC sp_MSforeachtable @command1 = 'SELECT * FROM ?'


--To delete all records in all tables in the database:

EXEC sp_MSforeachtable @command1 = 'DELETE FROM ?'

--To Truncate all tables in the database:

EXEC sp_MSforeachtable @command1 = 'TRUNCATE TABLE ?'

--To drop all the tables:
EXEC sp_MSforeachtable @command1 = 'DROP TABLE ?'


No comments:

Post a Comment