Martin Smaith 的回答是我首选的解决方案,但我可以建议另外两种方法:
1)您可以在SSMS中使用“SQLCMD模式”。
它看起来像:
:connect MyServer -U MyLogin -P MyComplexPassword
--Then have some code
:connect MyOtherServer ...
--Then have some code
但是你不能循环,所以你会有重复的代码。
或者
2) 您可以基于服务器列表创建一个带有 FOR 循环的 CMD 文件。这是我自己酿造的一个例子。只需将其复制粘贴到 REQ.CMD 并创建一个名为 SERVERS.LST 的文本文件,每行有一个服务器名称。连接将通过 Windows 身份验证。如果愿意,您可以将 OSQL 更改为 SQLCMD,但 OSQL 应该适用于 SQL 2008。
REM To execute a SQL command or file to multiple servers
REM Using a server list file
REM And using 2 kind of parameters (script file or query)
REM Pollus Brodeur - June 2007
@echo off
set PARAM1=%1
set PARAM2=%2
set PARAM3=1
REM You need at least 1 parameter
if x==%1x goto ERROR1
if EXIST %PARAM1% (set ISFILE=1) else (set ISFILE=0)
REM Setting Servers List File and verify file existance or X
if x==%2x (set PARAM2=servers.lst)
if X==%2 (set PARAM3=0 & set PARAM2=servers.lst & goto MAIN)
if NOT EXIST %PARAM2% (goto ERROR2)
REM Not interactive
if X==%3 (set PARAM3=0)
:MAIN
echo ===============================================================================
echo REQ - Execute a SQL command or file to multiple servers using a list file
echo %DATE% %TIME%
if %PARAM3%==0 (echo Non Interactive mode)
echo ===============================================================================
if %ISFILE%==0 (GOTO COMMAND)
echo For following file :
echo %PARAM1%
goto EXEC
:COMMAND
echo For following command :
echo %PARAM1%
:EXEC
echo ===============================================================================
echo For following servers :
type %PARAM2%
echo ===============================================================================
if %PARAM3%==1 (echo Interactive mode. Use X parameter to deactivate & pause)
echo Exec...
if NOT EXIST .\out mkdir out
if EXIST out\req.out (del out\req.out)
if %ISFILE%==0 (GOTO COMMAND1)
for /F %%a in (%PARAM2%) do echo %%a & osql -S %%a -E -n -h-1 -w 9999 -u -i %PARAM1% -o out\req.out.%%a.txt
goto ENDEXEC
:COMMAND1
for /F %%a in (%PARAM2%) do echo %%a & osql -S %%a -E -n -h-1 -w 9999 -u -Q %PARAM1% -o out\req.out.%%a.txt
:ENDEXEC
type out\req.out.*.txt >> out\req.out 2>&1
echo ===============================================================================
echo Execution is done. Output files are in .\out
echo more /E /C out\req.out.*.txt
echo more out\req.out
echo ===============================================================================
if %PARAM3%==1 (pause)
goto END
:ERROR1
goto CALLEXAMPLE
:ERROR2
echo Error: Server File List named %PARAM2% doesn't exists
goto CALLEXAMPLE
:CALLEXAMPLE
echo -------------------= REQ call examples =--------------------
echo REQ.cmd Param1 Param2 Param3
echo Param1 = command or scriptfile.sql {mandatory}
echo Param2 = servers list file {servers.lst per default}
echo Param3 = X {for non interactive mode}
echo ------------------------------------------------------------
:END