-
Notifications
You must be signed in to change notification settings - Fork 35
Description
When running an INSERT command, the database operation succeeds, but I get a "Cannot find table 0" error in PowerShell:
Cannot find table 0.
At C:\Users\replica\Documents\WindowsPowerShell\Modules\MyModule\Internal\Invoke-SqlCmd2.ps1:522 char:21
+ $ds.Tables[0]
+ ~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException
+ FullyQualifiedErrorId : System.IndexOutOfRangeException
I found an answer on Stack Overflow that describes a similar issue - since an INSERT naturally doesn't produce any output, the function is trying to reference row 0 in an empty collection.
My proposed solution is to wrap the switch
block near the end of the function in an if
:
if ($ds.Tables.Count -gt 0)
{
switch ($As)
{
# ...
}
}
else
{
Write-Verbose "No output was returned from the SQL instance."
}
I thought about just wrapping specific cases in the switch block, but there are two that use that index behavior ($ds.Tables[0]
), and I'm not certain it's a big deal if the function doesn't provide output in this case, rather than providing a DataTable or DataSet object that contains no tables or rows. I could definitely be wrong, though, as I'm still wrapping my mind around SQL stuff.
I've tested this change and confirmed that it seems to be working for me - the INSERT succeeds, there's a verbose message and no error, and there's no output. I can submit a PR if you all would like.
Thanks!
~replica
This issue is copied over from issue 19 on ramblingcookiemonster's original version of Invoke-SqlCmd2.