0

我正在尝试使用 sqlcmd 实用程序执行 4000+(约 140GB)脚本。

这样做的原因是从 SQL Server 2017 到 2008 的所有导出选项都因错误而失败,所以我决定使用 SSMS 中的“生成脚本”编写整个数据库的脚本,然后通过批处理文件执行所有生成的脚本并记录每一个错误,所以我可以查明每个脚本中的问题是(或不是)。

到目前为止,我设法确定 2008 并不真正喜欢某些表中的日期格式,这很奇怪,因为说 DB 在今年早些时候从 SQL SRV 2008 导出到 2017。

不管怎样,我写的 bach 脚本是这样的:

for %%G in (*.sql) do (

if not %errorlevel% == 0 echo %errorlevel% >> errorlog.txt 2>&1
if %errorlevel% == 0 sqlcmd /S SQLINSTANCE /d DBNAME -E -i"%%G"

)

pause

该脚本正确执行(一次插入 1 行),但创建和附加“errorlog.txt”除外 - 该文件甚至没有在进程中创建,当我尝试手动创建它时,没有任何内容附加到该文件. 当我尝试在第 4 行创建“successlog.txt”时,该文件已正确创建并附加。

请问有人对我现在可以采取的步骤有任何指导吗?

4

1 回答 1

0

您可以在 BAT 文件中调用子任务,并在那里检查错误级别。就是这样:

@Echo Off
:: Making sure the errorlevel is zero by listing all files in current folder 
:: without showing them.
dir >Nul 2>&1
:: This loop calls the subtask with the G-parameter, ie. the SQL-file path.
for %%G in (*.sql) do (
   call :my_subtask "%%~G"
)
:: Skipping to the end -section.
goto :end

:my_subtask
if %errorlevel% NEQ 0 echo %errorlevel% >> errorlog.txt 2>&1
if %errorlevel% EQU 0 sqlcmd /S SQLINSTANCE /d DBNAME -E -i "%~1"
:: NOTE the path of the SQL-file is now in the %1 -parameter.
:: It is good practice to use the "%~1" notation.
:: 
:: Returning to for-loop.
goto :EOF

:end
@Echo On

但是,我会将子任务编码为有点不同,如下所示:

:my_subtask
@Echo on
sqlcmd /S SQLINSTANCE /d DBNAME -E -i "%~1" >> successlog.txt 2>>errorlog.txt
@Echo off
if %errorlevel% NEQ 0 (
   Echo %~0 The subtask calling %~1 failed, errorlevel was %errorlevel% 
)
goto :EOF
于 2021-12-07T10:35:13.283 回答