如何逐个运行bcp命令

时间:2016-04-19 07:05:48

标签: bcp errorlevel sql-server-bcp

我想在一个批处理文件/脚本中逐个执行15个“bcp命令”。 只有在成功执行上一个命令后,才能处理或执行每个命令。 如果在任何情况下命令都无法执行......脚本应该停止执行...

我试过这个..但我没有得到足够的输出我需要的东西..

staticFileLocation("/public");

2 个答案:

答案 0 :(得分:0)

我认为您缺少的是整个脚本停止了。您目前的pause命令暂时保存脚本,但不保存完整脚本。

您应该使用标签跳转到。在下面的脚本中,我添加了标签:error_happened,以防出现错误。如果没有错误,则命令goto :EOF将跳过:error_happened标签。

bcp.exe "select * from OrderXpress.dbo.Customers where CustId < 1000" queryout "D:\Customer.dat" -S localhost -U sa -P Sa12345 -E -n  
IF ERRORLEVEL 1 GOTO error_happened

bcp.exe OrderXpress.dbo.Customers out "D:\Customer2.dat" -S localhost -U sa -P Sa12345 -E -n 
IF ERRORLEVEL 1 GOTO error_happened

bcp.exe OrderXpress.dbo.Orders out "D:\Orders.dat" -S localhost -U sa -P Sa12345 -E -n 
IF ERRORLEVEL 1 GOTO error_happened

goto :EOF

:error_happened
echo,
echo An error has occurred. Script stopped
echo
pause

但是必须针对BCP产生的错误级别进行说明。如果没有正确导出数据行,那么我不确定错误级别会发生什么。我知道在导入时出现行错误不会导致问题。另请参阅:https://groups.google.com/forum/#!topic/microsoft.public.sqlserver.tools/qzpWuZzJnr4

我有使用-e参数检查错误的解决方法。该脚本将是:

bcp.exe "select * from OrderXpress.dbo.Customers where CustId < 1000" queryout "D:\Customer.dat" -e errors.txt -S localhost -U sa -P Sa12345 -E -n  
IF ERRORLEVEL 1 GOTO error_happened
call :check_errorfile

bcp.exe OrderXpress.dbo.Customers out "D:\Customer2.dat" -e errors.txt -S localhost -U sa -P Sa12345 -E -n 
IF ERRORLEVEL 1 GOTO error_happened
call :check_errorfile

bcp.exe OrderXpress.dbo.Orders out "D:\Orders.dat" -e errors.txt -S localhost -U sa -P Sa12345 -E -n 
IF ERRORLEVEL 1 GOTO error_happened
call :check_errorfile

goto :EOF

:check_errorfile
if exist errors.txt (
    FOR %%A IN (errors.txt) DO (
        if %%~zA GTR 0 (
        goto error_happened
        ) else (
        del errors.txt
        )
    )
)
exit /b

:error_happened
echo,
echo An error has occurred. Script stopped
echo
pause

答案 1 :(得分:-1)

请试试这个......

开始尝试     bcp.exe&#34;从OrderXpress.dbo.Customers中选择*,其中CustId&lt; 1000&#34; queryout&#34; D:\ Customer.dat&#34; -S localhost -U sa -P Sa12345 -E -n

结束尝试

BEGIN CATCH

DECLARE @msg VARCHAR(1000)

SET @msg = ERROR_MESSAGE()

RAISERROR(@msg,16,0)

END CATCH

相关问题