Saturday, February 25, 2012

run a .sql in different databases

I want to know if it is posible to run one query file in different databases

right now I have 2 different .sql and 6 databases and I want to run it in the following order

queries1.sql on db1
quieries2.sql on db2
quieries1.sql on db3
queries2.sql on db4
quieries1.sql on db5
queries2.sql on db6

all this just in one execution and they cannot run at the same time

Check the utility SQLCMD.EXE in BOL, or OSQL.EXE if you are using SS 2000.

AMB

|||im using MSSQL server 2005
|||

Relatively simple using a SQLCmd.exe script.

Refer to Books Online for the complete syntax, description, and samples.

|||i found this

Code Snippet

Create a folder named MyFolder. Use the File/Save As menu to save the above script as a file named MyScript.sql in the folder C:\MyFolder. Run the following command from the command prompt to run the script and place the output in a file named MyOutput.txt in the same folder:


sqlcmd -i C:\MyFolder\MyScript.sql -o C:\MyFolder\MyOutput.txt

When you view the contents of MyOutput.txt in Notepad, you will see the following:


Changed database context to 'AdventureWorks'.
ContactID FirstName LastName
-- -- --
1 Syed Abbas
2 Catherine Abel
3 Kim Abercrombie
4 Humberto Acevedo
5 Pilar Ackerman

(5 rows affected)


but how can I say to it, run myscript.sql in the database db1 for example
|||

Check BOL for more info about SQLCMD.EXE parameters.

-d use database name

AMB

|||you mean something like this?

sqlcmd -i C:\MyFolder\MyScript.sql -d db1 -o C:\MyFolder\MyOutput.txt
|||

Something I've done to execute a script against multiple databases is a DOS call.

Command Line Reference

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_o.mspx?mfr=true

for /F ["usebackqParsingKeywords"] {%% | %}variable in (`command`) do command [CommandLineOptions]

Here we go

for /F %a in ('select [name] from sysdatabases') do isql /E /i sql_script /d %a

The sqlcmd call is not much different than isql. I've also used this method to execute a script against multiple database servers. It can get a bit ugly, but it does the trick.

Good luck,

Bruce.

No comments:

Post a Comment