【问题标题】:Sql script runnerSql 脚本运行器
【发布时间】:2013-01-11 15:58:13
【问题描述】:
Get-ChildItem ".\Stored Procedures\*.sql" | ForEach-Object { sqlcmd -S ServerName -d     DatabaseName -E -i $_.FullName }

当我使用上述命令从文件夹中运行一批脚本时,如果中间脚本中仍然存在问题(如中间的 create/Alter/DROP DML 脚本),那么它应该只停在那里,需要给我一个错误信息。

【问题讨论】:

    标签: sql sql-server powershell scripting


    【解决方案1】:

    你需要做一些事情:

    1. 将 ErrorActionPreference 设置为停止
    2. 在 sqlcmd.exe 实用程序中使用 -b 参数
    3. 捕获并记录或显示 sqlcmd.exe 实用程序的输出

    answered a similar a question on another forum 并在这里重新发布了答案:

    echo "select 'Good 1'" > C:\temp\scripts\1.sql
    echo "select * from missingTable" > C:\temp\scripts\2.sql
    echo "Select 'Good 3'" > C:\temp\scripts\3.sql
    
    $ErrorActionPreference = "Stop"
    
    ForEach ($S In Gci -Path "C:\Temp\Scripts\" -Filter *.sql | Sort-Object Name) {
        try { 
            $result = SqlCmd -b -S $env:computername\sql1 -i $S.FullName
            $result = $result -join "`n"
    
            if ($LASTEXITCODE -ne 0) {
                throw "$S.FullName : $lastexitcode : $result"
            }
            else {
                write-output "Success: $($s.fullname) : $result" | Out-File C:\Temp\Scripts\sqllogging.txt -Append
            }
        }
        catch {
            write-output "Failed: $_ " | Out-File C:\Temp\Scripts\sqllogging.txt -Append
            throw
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 2014-07-29
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2013-10-19
      • 2013-01-18
      相关资源
      最近更新 更多