Question: I have a SQL script I need to run on about 20 different databases.

I basically just need to be able to run some SQL, then have it load and run a file from the disk, do more SQL, run that same script again, etc.

I was hoping to make a SQL script that would basically look something like this:

```
use database1
go
exec c:\release.sql
go

use database2
go
exec c:\release.sql
go

use database3
go
exec c:\release.sql
go

```

--etc....

I've looked online a bunch and found a way to do something similar in a batch file with sqlcmd but it isn't working and I don't see how to switch databases that way, either.

Thanks a ton!

Ben

Answer: 
You can switch management studio to sqlcmd mode (query menu) and then run a script with `:r script.sql` 

To do this on a dynamically generated list of databases you have to do some sqlcmd trickery:

* set output to file
* generate the command to execute
* set output to stdout
* execute the file
* delete the temp file

I assume in this example that the file script.sql exists in `c:\temp`. Note that the `GO` statements are important in the script or the sqlcmd parser will get confused.

```
:OUT $(TEMP)\db.sql
declare @script nvarchar(max)
select @script = isnull(@script, '') 
               + 'use ' + name + char(13) + char(10) 
               + ':r c:\temp\script.sql' + char(13) + char(10) 
  from sys.databases
 where name like N'%[_]db'
print @script

GO

:OUT stdout
:r $(TEMP)\db.sql

GO

!!del $(TEMP)\db.sql /s /q

```
Thanks everyone who pitched in! The following seems like it might work (based on @srutzky's answer)

> 
> sqlcmd -S "localhost" -E -i "c:\release.sql" -d database1 -o results.txt
> 
> 
> 

The thing I am missing by using a cmd prompt instead of SSMS is that I don't think I can write cursor to loop through each database that ends with "\_db" and then execute against that... Here's the SQL I have but I just need to be able to put the link to the SQL file to execute.

[link](http://screencast.com/t/F7exp9xzV2j)

If I put the release script SQL into this file into the @text variable it doesn't work because it blows up on each GO statement I have in my release.sql file.

```
declare @text as nvarchar(max)
set @text = N'
-- GET AND RUN SCRIPT FROM DISK!
'

declare C_CURSOR CURSOR FOR 
    select  [Name] from sys.databases 
    where   name like '%_db' 
    order by name

declare @runtext as nvarchar(max)
declare @DB_Name as nvarchar(200)

OPEN C_CURSOR
fetch next from C_CURSOR INTO @DB_Name
WHILE(@@FETCH_STATUS = 0)
BEGIN

    print @DB_Name
    set @runtext = 'select ''' + @DB_Name + ''' as DatabaseName
        use ' + @DB_Name + N'
    ' + @text

    exec sp_executesql  @runtext

    fetch next from C_CURSOR INTO @DB_Name
END

CLOSE C_CURSOR
DEALLOCATE C_CURSOR

```

Thanks again!