我有一个使用 Write-SqlTableData 的 powershell 脚本(来自 SqlServer 模块)在三个位置将 PSCustomObjects 写入(已存在的)数据库表,如下所示:
# Note that for some reason, PSCustomObjects created by Select-Object don't always work well with
# Write-SqlTableData, whereas "[PSCustomObject] @{ ... }" does.
$userDataRows = $users | Sort-Object id | ForEach-Object { [PSCustomObject] @{
id = $_.id;
name = $_.name;
employee_num = [string]($_.employee_num) }}
# Be careful with -Force, because the column types appear to be based on the *first row only*, and if it contains
# a $null value its corresponding column will be of type SQL_VARIANT.
$userDataRows | Write-SqlTableData -ServerInstance '.' -Database 'MyDB'-SchemaName 'Staging' -TableName 'User'
在我的开发机器上,即使导入大约 18000 行,也不会出现任何问题。但是,在生产计算机上,对 Write-SqlTableData
的调用失败并出现以下错误:
Write-SqlTableData : Failed to connect to server ..
At D:\Scripts\MyScript.ps1:155 char:25
+ ... eDataRows | Write-SqlTableData -ServerInstance '.' -Database 'MyDB' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.:String) [Write-SqlTableData], ConnectionFailureException
+ FullyQualifiedErrorId : ConnectionToServerFailed,Microsoft.SqlServer.Management.PowerShell.WriteSqlTableData
奇怪的是,它并不总是在同一点上失败 - 通常在导入第三组数据时会失败,但偶尔会在导入第二组数据时失败。另外,通常会插入一些行,但它们的数量有所不同:有时 99,有时 141...
谁能告诉我为什么在导入过程中会出现“无法连接到服务器”的信息?
编辑:总结一下我在一些评论中回复的内容:不涉及网络,开发和生产机器都使用相同的 SQL Server 版本,并且不涉及多线程。此外,脚本失败的速度太快,不会导致超时。
最佳答案
解决了!长话短说,我现在使用 -InputData
参数调用 Write-SqlTableData
,而不是通过管道将数据传递给它。
也就是说,改变
$userDataRows | $userDataRows |写入SqlTableData ...
进入
Write-SqlTableData -InputData $userDataRows ...
...似乎已经解决了我的问题。此外,插入 18000 行现在需要 2 秒,而不是 3.5 分钟。
这背后的原因很可能是,将 Write-SqlTableData 调用更改为使用 -InputData 意味着它会立即获取所有 18000 个 PSCustomObject,并使其能够以批量方式执行插入。这可以避免“无法连接到服务器”错误并提供更好的性能。
我已经写了完整的解释here .
关于sql - Write-SqlTableData 失败,ConnectionToServerFailed 中途失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67162795/