I have several databases (SqlServer 2005) on the same server with the same schema but different data.
I have one extra database which has one table storing the names of the mentioned databases.
So what I need to do is to iterate over those databases name and actually "switch" to each one (use [dbname]) and execute a T-SQL script. Am I clear?
Let me give you an example (simplified from the real one):
CREATE TABLE DatabaseNames
(
Id int,
Name varchar(50)
)
INSERT INTO DatabaseNames SELECT 'DatabaseA'
INSERT INTO DatabaseNames SELECT 'DatabaseB'
INSERT INTO DatabaseNames SELECT 'DatabaseC'
Assume that DatabaseA, DatabaseB and DatabaseC are real existing databases.
So let’s say I need to create a new SP on those DBs. I need some script that loops over those databases and executes the T-SQL script I specify (maybe stored on a varchar variable or wherever).
Any ideas?
I guess this will generally not be possible in TSQL, since, as others pointed out,
you first need as USE statement to change the database,
followed by the statement you want to execute, which is, although not specified, a DDL statement which must be first in a batch.
Moreover, you cannot have a GO in a string to be EXECuted.
I found a command-line solution invoking sqlcmd:
Sample code uses current Windows login to query all active databases from Master (replace with your own connection and query for databases), and executes a literal TSQL command on each database thus found. (line breaks for clarity only)
Have a look at the command-line parameters of sqlcmd. You can pass it a TSQL file as well.
If you want to allow manual selection of databases, have a look at SSMS Tools Pack.