Home > Functions and DMVs, SQL Queries, SQL Server, Stored Procedures, System Stored Procs, T-SQL > Perform an action on all tables in a database using ‘sp_msforeachtable’

Perform an action on all tables in a database using ‘sp_msforeachtable’

You might have faced a challenge to perform some operation on all the tables in a database. For example truncate all the tables in a database ( no one would have faced this :-) ) , space used by all tables etc.
You can use the system stored procedure “sp_msforeachtable” to achieve your task.
The parameter to this stored proc is the script that needs to be executed. It executed the script for all the tables in the database

example :
exec sp_msforeachtable ‘truncate table ?’
exec sp_msforeachtable ‘sp_spaceused ?’

here the ‘?’ represents the tablename. You need to be really careful while executing this command , as even a small mistake can be sometimes catastrophic.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: