Skip to content

"Cannot find table 0" on running an INSERT #5

@replicaJunction

Description

@replicaJunction

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions