Extract from sql.to multiple sheets

  • Import-Module ImportExcel

    # Path to your .sql file

    $sqlFile = "C:\Data\MyQueries.sql"

    $excelPath = "C:\Data\SqlExtract_$(Get-Date -Format yyyyMMdd).xlsx"

    # Read the SQL text

    $sql = Get-Content $sqlFile -Raw

    # Run SQL and get multiple result sets

    $resultSets = Invoke-Sqlcmd -ServerInstance "MyServer" -Database "MyDB" -Query $sql -OutputAs DataTables

    # Loop through each result set and export to Excel

    $sheetNumber = 1

    foreach ($table in $resultSets.Tables) {

    $sheetName = "Sheet$sheetNumber"

    $table | Export-Excel -Path $excelPath -WorksheetName $sheetName -AutoSize -Append

    $sheetNumber++

    }

    Write-Host "✅ Exported $($resultSets.Tables.Count) result sets to $excelPath"

Viewing post 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply