在具有不同参数的 .bat 文件中循环

Loop in a .bat file with different parameters

我有一个 .bat 文件,它以 PDF 格式呈现 SSRS 报告。该报告接受 2 个参数 studentID 和 SubjectID。当我尝试传入每个 studentID 和 SubjectID 时,这运行良好。

我希望 .bat 文件执行一个存储过程,其中包含学生 ID 和 SubjectID 的列表,并且 run/loop 每个 StudentID 和 SubjectID。 下面是.bat文件代码。

@setlocal enableextensions enabledelayedexpansion
@echo off
Set varServerPath=http://xyz/ReportServer

sqlcmd -Q "exec dbo.Storedproc_Studentlist" -S ServerName -d DatabaseName 

LOOP:

rs -i C:\ReportRender\Student.rss -s%varServerPath% -e Exec2005 -v studentid="36" -v subjectid="500" -v vOutputFilePath="C:\ReportRender\Output\ZYZReport.pdf"  -v vReportPath="/Student Reports/ReportName.rdl" -l 900 


pause
exit

我如何为存储过程的每个结果循环遍历 "rs" 命令

dbo.Storedproc_Studentlist

这个存储过程returns

SELECT '1' AS RowNumber,'1789' StudentID, '364' SubjectID, 'C:\Reports\tmurray' OutputLocation
UNION ALL
SELECT '2' AS RowNumber,'1789' StudentID, '365' SubjectID, 'C:\Reports\tmurray' OutputLocation
UNION ALL
SELECT '3' AS RowNumber,'1780' StudentID, '364' SubjectID, 'C:\Reports\mdbrisbin' OutputLocation

谢谢,

命令 FOR 可用于 运行 来自批处理文件的循环中的命令。

这是一种可能的解决方案:

@echo off
setlocal EnableExtensions
set "ListFile=%TEMP%\StudentList.tmp"
set "varServerPath=http://xyz/ReportServer"

if exist "%ListFile%" del "%ListFile%"
sqlcmd.exe -Q "exec dbo.Storedproc_Studentlist" -S ServerName -d DatabaseName >"%ListFile%" 2>nul
if exist "%ListFile%" (
    for /F "usebackq tokens=5,7 delims=', " %%A in ("%ListFile%") do (
        echo Processing student with id %%A and subject with id %%B ...
        rs.exe -i C:\ReportRender\Student.rss -s%varServerPath% -e Exec2005 -v studentid="%%A" -v subjectid="%%B" -v vOutputFilePath="C:\ReportRender\Output\ZYZReport.pdf" -v vReportPath="/Student Reports/ReportName.rdl" -l 900
    )
    del "%ListFile%"
)

endlocal
pause

在不使用临时列表文件的情况下直接处理 sqlcmd.exe 的输出也可能有效。

@echo off
setlocal EnableExtensions
set "varServerPath=http://xyz/ReportServer"

for /F "tokens=5,7 delims=', " %%A in ('sqlcmd.exe -Q "exec dbo.Storedproc_Studentlist" -S ServerName -d DatabaseName 2^>nul') do (
    echo Processing student with id %%A and subject with id %%B ...
    rs.exe -i C:\ReportRender\Student.rss -s%varServerPath% -e Exec2005 -v studentid="%%A" -v subjectid="%%B" -v vOutputFilePath="C:\ReportRender\Output\ZYZReport.pdf" -v vReportPath="/Student Reports/ReportName.rdl" -l 900
)

endlocal
pause

要了解使用的命令及其工作原理,请打开命令提示符 window,在其中执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • echo /?
  • if /?
  • del /?
  • set /?
  • setlocal /?
  • endlocal /?
  • for /?
  • pause /?
  • exit /?

另请参阅有关 Using command redirection operators 的 Microsoft 文章,了解 >2>nul 的解释。

第二批代码中命令 FOR 中的 2>nul 中的重定向运算符 > 必须使用 ^ 进行转义才能在执行时应用sqlcmd.exe 并且未被解释为命令 FOR 在命令行中无效位置的重定向运算符,导致在没有 ^ 的情况下执行批处理文件时出现语法错误.