在批处理脚本中使用Sql变量

时间:2014-02-28 14:11:42

标签: sql sql-server batch-file cmd

我已经查看了许多涉及此问题的帖子,但我无法将建议应用于我的情况。 我希望只有当file1存在且sql命令的行计数返回大于0的计数时才能运行代码块。两者都必须为true才能运行代码块(:RUNCODE)。我设置了一些IF来处理它,它跳转到:RUNCODE或:END。

    SET SqlServerName="SERVER1"
    SET SqlDatabaseName="DB1"
    SET SQL="SELECT COUNT(*) FROM TABLE1" 

    SQLCMD.exe -S%SqlServerName% -E -d%SqlDatabaseName%  -Q%SQL% -h -1 -o RowCount.txt

    SET /p RowCount= <RowCount.txt
    DEL RowCount.txt

    echo %RowCount%


    IF EXIST "File1" IF %RowCount% GTR 0 
    (
            ECHO Running the position Loader for EFA...
            GOTO RUNCODE
     )


    IF NOT EXIST "File1" IF %RowCount% EQU 0
    (              
            ECHO The Position File Does not Exist...
            GOTO END
    )

    IF EXIST "File1" IF %RowCount% EQU 0
    (
            ECHO The File Does not Exist...
            GOTO END
    )

    IF NOT EXIST "File1" IF %RowCount% GTR 0
    (
            ECHO The Position File Does not Exist...
            GOTO END 
    )

    :RUNCODE 
    echo Running code block now now...
    EXIT

    :END
    echo conditions not met...
    EXIT

上面的代码给了我RowCount = 0(变量中有空格) 并且似乎完全跳过if条件。

非常感谢任何帮助。

输出脚本的示例。请注意,0前面有空白区域,而前面没有(1行受影响)

      0
     

(受影响的一行)

1 个答案:

答案 0 :(得分:2)

IF的左括号需要在同一行。

IF EXIST "File1" IF %RowCount% GTR 0 (
        ECHO Running the position Loader for EFA...
        GOTO RUNCODE
)


IF NOT EXIST "File1" IF %RowCount% EQU 0 (              
        ECHO The Position File Does not Exist...
        GOTO END
)

IF EXIST "File1" IF %RowCount% EQU 0 (
        ECHO The File Does not Exist...
        GOTO END
)

IF NOT EXIST "File1" IF %RowCount% GTR 0 (
        ECHO The Position File Does not Exist...
        GOTO END 
)

以下是如何在没有空格的情况下获取rowcount

SET SQL="SET NOCOUNT on SELECT COUNT(*) FROM dbo.ACCT" 

SQLCMD.exe -S%SqlServerName% -E -d%SqlDatabaseName%  -Q%SQL% -h -1 -o RowCount.txt
for /f "delims=" %%a in ('type Rowcount.txt') do Call :Trim rcount %%a
if /i exist RowCount.txt DEL /f /q RowCount.txt
echo %rcount%
exit /b

:Trim <return> <string>
for /f "tokens=1*" %%a in ("%*") do set "%%a=%%b"
exit /b