Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Run SQL code on each database

By Ashley McLellan,

Now there is a non-documented Stored Procedure on SQL Server that will let you run some SQL on each Database. A very handy stored proc, when I went and had a look a the back end of it however I felt it could be a bit better and simpler. So I made the below, its basically Dynamic SQL and I just pass in the Database and each SQL Command to run. There are 5 commands in total that you can feed in to run, 3 of these will run on each of the databases, the other two are a pre Command to run first and a post Command to run at the end of the process. There is a variable '?' which will be replaced with the current database name. This can be used to determine if the current database is to run the command or not. You can also alter the insert into the @DBs temp table if you wish to only ever use certain Databases if you choose. Example of use exec sp_foreachDB @Command1 = ' if ''?'' not like ''%master%'' begin select DB_NAME() end' ,@Command2 = 'PRINT ''?''' ,@Command3 = 'PRINT ''Ash Rocks''' ,@PreCommand = 'PRINT ''Starting App''' ,@PostCommand = 'PRINT ''Finished App'''

Total article views: 2400 | Views in the last 30 days: 11
 
Related Articles
FORUM

is there command to run and see who is locking or if there is any problems with specific database

is there command to run and see who is locking or if there is any problems with specific database

FORUM

database diagram print on one page

database diagram print

FORUM

Exporting and Printing Database Diagrams on large paper stock

Seeking info on exporting and printing database diagrams

FORUM

Database Diagram printing problems

Anyone know how to resolve printing problems?

BLOG

Database Creation using Create Database command

In SQL Server, database can be created by 2 ways:-  Using Create Database command Using SQL Sever M...

Tags
t-sql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones