@@ -991,7 +991,18 @@ WHERE c.object_id = OBJECT_ID(@tableName)
991991 foreach ($instance in $SqlInstance ) {
992992 $elapsed = [System.Diagnostics.Stopwatch ]::StartNew()
993993 # Open Connection to SQL Server
994+ # Detect if user passed an already-open connection that we should preserve
995+ $startedWithAnOpenConnection = $false
994996 try {
997+ # Check if user passed a Server SMO object with an open connection
998+ # Following the pattern from Invoke-DbaQuery.ps1
999+ if ($instance.InputObject.GetType ().Name -eq " Server" -and
1000+ (-not $SqlCredential ) -and
1001+ ($instance.InputObject.ConnectionContext.DatabaseName -eq $Database -or -not $Database )) {
1002+ $startedWithAnOpenConnection = $true
1003+ Write-Message - Level Debug - Message " User provided an open connection - will preserve it after import"
1004+ }
1005+
9951006 $server = Connect-DbaInstance - SqlInstance $instance - SqlCredential $SqlCredential - Database $Database - MinimumVersion 9
9961007 $sqlconn = $server.ConnectionContext.SqlConnectionObject
9971008 if ($sqlconn.State -ne ' Open' ) {
@@ -1409,10 +1420,13 @@ WHERE c.object_id = OBJECT_ID(@tableName)
14091420 }
14101421 }
14111422
1412- try {
1413- $sqlconn.Close ()
1414- $sqlconn.Dispose ()
1415- } catch {
1423+ # Only close connection if we created it (not user-provided)
1424+ if (-not $startedWithAnOpenConnection ) {
1425+ try {
1426+ $sqlconn.Close ()
1427+ $sqlconn.Dispose ()
1428+ } catch {
1429+ }
14161430 }
14171431
14181432 try {
@@ -1461,10 +1475,16 @@ WHERE c.object_id = OBJECT_ID(@tableName)
14611475 }
14621476 end {
14631477 # Close everything just in case & ignore errors
1478+ # Only close SQL connection if we created it (not user-provided)
14641479 try {
1465- $null = $sqlconn.Close (); $null = $sqlconn.Dispose ();
1466- $null = $bulkCopy.Close (); $bulkcopy.Dispose ();
1467- $null = $reader.Close (); $null = $reader.Dispose ()
1480+ if (-not $startedWithAnOpenConnection ) {
1481+ $null = $sqlconn.Close ()
1482+ $null = $sqlconn.Dispose ()
1483+ }
1484+ $null = $bulkCopy.Close ()
1485+ $bulkcopy.Dispose ()
1486+ $null = $reader.Close ()
1487+ $null = $reader.Dispose ()
14681488 } catch {
14691489 # here to avoid an empty catch
14701490 $null = 1
0 commit comments