DOS批处理文件 - 循环并递增1

时间:2011-02-01 04:51:10

标签: sql batch-file cmd

我有这个批处理文件,登录到远程机器上的sql运行存储过程,然后将输出发送到文本文件。我希望它将IP地址中的第3个八位字节和输出文本文件的名称递增1并循环,这样我就不必一遍又一遍地重复命令。此外,我希望它达到一定数量时停止。有没有办法做到这一点?

sqlcmd -U user -P password -S 192.168.1.2 -i c:\sql\storecreditfix.sql -o c:\sql\ouput01.txt
sqlcmd -U user -P password -S 192.168.2.2 -i c:\sql\storecreditfix.sql -o c:\sql\ouput02.txt
sqlcmd -U user -P password -S 192.168.3.2 -i c:\sql\storecreditfix.sql -o c:\sql\ouput03.txt
sqlcmd -U user -P password -S 192.168.4.2 -i c:\sql\storecreditfix.sql -o c:\sql\ouput04.txt
sqlcmd -U user -P password -S 192.168.5.2 -i c:\sql\storecreditfix.sql -o c:\sql\ouput05.txt

3 个答案:

答案 0 :(得分:8)

这将做你想要的。 / L说明符告诉它像循环的常规编程。第一个参数是起始整数,下一个是要步的数字,最后一个是计数。所以这将从1开始循环,对6个整数递增1:

@echo off
FOR /L %%G IN (1, 1, 6) DO (
     echo sqlcmd -U user -P password -S 192.168.%%G.2 -i c:\sql\storecreditfix.sql -o c:\sql\ouput0%%G.txt
)

如果你想做一个IP列表而不是一个范围,你可以不用/ L,只列出数字。例如     FOR %% G IN(1,2,3,9,12,121)DO ...

显然,sqlcmd之前的“echo”仅用于测试;)

答案 1 :(得分:2)

假设您实际使用cmd.exe而不是MS-DOS,增量和测试变量的一种方法如下:

    @setlocal enableextensions enabledelayedexpansion
    @echo off
    set /a "i = 1"
:loop
    if !i! leq 15 (
        if !i! lss 10 (
            echo sqlcmd -S 192.168.!i!.2 -o c:\sql\ouput0!i!.txt
        ) else (
            echo sqlcmd -S 192.168.!i!.2 -o c:\sql\ouput!i!.txt
        )
        set /a "i = i + 1"
        goto :loop
    )
    endlocal

这是你所需要的略微修改版本,它回应相关位而不是执行它们,并输出:

sqlcmd -S 192.168.1.2 -o c:\sql\ouput01.txt
sqlcmd -S 192.168.2.2 -o c:\sql\ouput02.txt
sqlcmd -S 192.168.3.2 -o c:\sql\ouput03.txt
sqlcmd -S 192.168.4.2 -o c:\sql\ouput04.txt
sqlcmd -S 192.168.5.2 -o c:\sql\ouput05.txt
sqlcmd -S 192.168.6.2 -o c:\sql\ouput06.txt
sqlcmd -S 192.168.7.2 -o c:\sql\ouput07.txt
sqlcmd -S 192.168.8.2 -o c:\sql\ouput08.txt
sqlcmd -S 192.168.9.2 -o c:\sql\ouput09.txt
sqlcmd -S 192.168.10.2 -o c:\sql\ouput10.txt
sqlcmd -S 192.168.11.2 -o c:\sql\ouput11.txt
sqlcmd -S 192.168.12.2 -o c:\sql\ouput12.txt
sqlcmd -S 192.168.13.2 -o c:\sql\ouput13.txt
sqlcmd -S 192.168.14.2 -o c:\sql\ouput14.txt
sqlcmd -S 192.168.15.2 -o c:\sql\ouput15.txt

只需将echo从线上取下并调整命令以放回其他位。

答案 2 :(得分:0)

如果您有权访问cmd.exe,那么您还可以访问cscript,它允许您在Javascript中编写DOS批处理文件。