Running SQLCMD in PowerShell via SQL Server Agent
Running SQLCMD in PowerShell via SQL Server Agent Learn how to execute a SQL query via SQL Server Agent using PowerShell and sqlcmd . This method ensures UTF-8 compatibility and proper handling of non-English characters. 1️⃣ Save Your SQL Query in a File First, create a SQL file with the query you want to execute. Save it as C:\Scripts\ExportQuery.sql . SET NOCOUNT ON; SELECT TOP 100 * FROM [YourDatabase].[dbo].[YourTable]; 2️⃣ Create a PowerShell Script Now, create a PowerShell script to execute the query and export the results as a CSV file. sqlcmd -S YourServer -E -i "C:\Scripts\ExportQuery.sql" -s "," -W -h -1 | Out-File "C:\Exports\ExportedData.csv" -Encoding UTF8 3️⃣ Configure SQL Server Agent Follow these steps to create a SQL Server Agent job: Open SQL Server Management Studio (SSMS). ...