将当前文件名从循环传递到批处理脚本中的标签

时间:2018-06-26 16:13:01

标签: batch-file error-handling sqlcmd

在批处理脚本中,我正在遍历SQL脚本文件夹的循环中运行sqlcmd。如果发生错误,我希望能够将当前正在处理的脚本/输出文件传递给循环外部的标签。

以下是示例代码:

@echo off
@setlocal enabledelayedexpansion

SET _INSTANCE=someinstance
SET _DATABASE=somedatabase
SET "_SCRIPTFOLDER=D:\Scripts for Testing"
SET "_OUTPUTFOLDER=D:\Output for Testing"

FOR %%S IN (
    "%_SCRIPTFOLDER%\*.sql"
) DO (

    SET /P _MSGa=Generating CSV: %%~nS.csv ... <NUL

    sqlcmd -b -S %_INSTANCE% -d %_DATABASE% -i "%%~fS" -s "|" -o "%_OUTPUTFOLDER%\%%~nS.csv" -W
    IF ERRORLEVEL >= 1 GOTO sqlcomderrorhandling

    SET /P _MSGb=file created. Removing header dashes ... <NUL

    REM REM Remove the line with dashes below the header
    @FINDSTR /r /b /v /c:"-*|" "%_OUTPUTFOLDER%\%%~nS.csv" > "%_OUTPUTFOLDER%"\tmp.txt
    IF ERRORLEVEL >= 1 GOTO findstrerrorhandling

    XCOPY /Y "%_OUTPUTFOLDER%"\tmp.txt "%_OUTPUTFOLDER%\%%~nS.csv" >NUL
    IF ERRORLEVEL >= 1 GOTO copyerrorhandling

    ECHO done.
)
DEL /Q /F "%_OUTPUTFOLDER%"\tmp.txt
GOTO done

:sqlcomderrorhandling
ECHO An error occurred while processing the file %%~nS.csv

:done
@pause

最后一个ECHO仅输出%〜nS.csv,而不是CSV文件的实际名称。我需要以某种方式利用功能来做自己想做的事吗?

1 个答案:

答案 0 :(得分:0)

根据rojo的第一句话和我的个人评论,这种结构是否更有意义?

@Echo Off

Set "_INSTANCE=someinstance"
Set "_DATABASE=somedatabase"
Set "_SCRIPTFOLDER=D:\Scripts for Testing"
Set "_OUTPUTFOLDER=D:\Output for Testing"

If Not Exist "%_OUTPUTFOLDER%\" (Echo Output folder doesn't exist
    Timeout 3 /NoBreak >Nul
    GoTo :EOF)

If Not Exist "%_SCRIPTFOLDER%\*.sql" (Echo Source folder doesn't contain any SQL files
    Timeout 3 /NoBreak >Nul
    GoTo :EOF)

CD /D "%_SCRIPTFOLDER%" 2>Nul || (Echo Source folder, %_SCRIPTFOLDER%, is not available.
    Timeout 3 /NoBreak >Nul
    GoTo :EOF)

For %%A In (*.sql) Do (
    Echo Generating CSV: %%~nA.csv ...
    SQLCmd -b -S %_INSTANCE% -d %_DATABASE% -i "%%A" -s "|" -o "%_OUTPUTFOLDER%\%%~nA.csv" -W 2>Nul && (
        Echo File created. Removing header dashes ...
        Findstr "[^-|]" "%_OUTPUTFOLDER%\%%~nA.csv">"%_OUTPUTFOLDER%"\%%~nA.tmp" && (
            Move /Y "%_OUTPUTFOLDER%"\%%~nA.tmp" "%_OUTPUTFOLDER%\%%~nA.csv">Nul 2>&1 || (
                Echo A Move error occurred while moving %%~nA.tmp
                Timeout 2 /NoBreak >Nul)) || (Echo A FindStr error occurred while removing header dashes 
            Timeout 2 /NoBreak >Nul)) || (Echo A SQLCmd error occurred while processing the file %%~nS.csv
            Timeout 2 /NoBreak >Nul))
Pause