Search This Blog

Traversing in all Tables of Database in SQL

Traversing in all Tables of  Database in SQL 

In order to Traverse through all tables of SQL like you want to get Counts of all Records of Each table in a Database or suppose you want to delete data of all tables of a Database for these type of requirement where you want a looping in all tables sql has provided a system stored Procedure sp_MSForEachTable

1-To Get count of all tables of a database

Select your DB Run below query

--Count all Records of all Tables in Database TestingNew

exec sp_MSforeachtable 'select ''?''[TableName], count(*)[Count] from Testingnew.?'


2-To Delete Data of all Tables of a Database donot apply into your working Database create a seprate Database with sample tables to test this query.

Select your Testing DB Run below query


-- delete data of all tables
EXEC sp_MSForEachTable 'DELETE FROM Test.?'

This will delete data of all tables of a database

Explanation-sp_MSforeachtable  traverse through all tables there is a question mark in the queries which denotes all Tables 

NOTE: If you want to run delete all data query where tables have foriegn key dependencies then you have to disable all Constraints first.



No comments:

Post a Comment