0

I want to export the results of a SQL Query to a CSV file in SQL Server Mgmt Studio, but not through the GUI. I want to do it automatically through my actual query. Is there an "Export to CSV" statement I can use in SQL Server? I have searched online and am only finding sites talking about how to export results to CSV through the GUI.

ANSWER

I utilized Powershell which is found in the this answer down in the below post:

Export query result to .csv file in SQL Server 2008

$AttachmentPath = "CV File location"
$QueryFmt= "Query"

Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $QueryFmt | Export-CSV $AttachmentPath
Crimp
  • 389
  • 1
  • 22

2 Answers2

1

Can you try if this will work on your side.

Use the SQLCMD utility to export the result of a query to a CSV file.

sqlcmd -S <SERVERNAME> -d <DATABASENAME> -E -s"," -W -Q "SELECT * FROM <TABLENAME>" -o "C:\PATH\TO\FILENAME.csv"
Michael C
  • 308
  • 1
  • 6
1

You have different ways

1.sqlcmd

https://learn.microsoft.com/en-us/sql/tools/sqlcmd/sqlcmd-utility?view=sql-server-ver16

example:

sqlcmd -S . -Q "select * from Employees;" -o "C:\employees.csv" -W -w 1024 -s "," -h-1

sqlcmd is the command name. -S . specifies the server name.

-Q "select * from Employees;" is the query that fetches data to be exported.

-o "C:\employees.csv" defines the file that stores the exported data.

-W removes the trailing white spaces you see in the command line tool output after each value. -w 1024 defines the length of the line in the CSV file.

-s "," defines the separator for the column values; here, a comma.

-h-1 removes the header.

2.SSIS

you can export data to a csv file using an SSIS package

https://www.mssqltips.com/sqlservertip/7209/export-data-to-excel-from-sql-server-integration-services-package/#:~:text=Double%2Dclick%20on%20the%20Flat,Delimited

3.C#

abolfazl sadeghi
  • 2,277
  • 2
  • 12
  • 20