Export SQL Server query to CSV using script

Mrye

Let say I have 1 query for remote SQL Server:

SELECT * FROM USER

And I would like to export using any kind of script without using manual intervention from SSMS. I expect the output to be like this:

id,username,firstName,lastName
1,amy,Amy,NULL
2,bob,Bob,Marley
3,cat,Cathy,NULL

How can I export into something like above?


I noticed there are few old discussions on this with variety of custom workaround that doesn't work for me. I prefer the exported file contains header, NULL value and without start/end quotes. Here's my closest script to achieve the result:

bcp "SELECT * FROM USER;" queryout export.csv -S 'localhost' -U sa -P 'password' -d 'mydatabase' -c -t  ',' 

Current output:

1,amy,Amy,
2,bob,Bob,Marley
3,cat,Cathy,
sacse

You can use SQLCMD to achieve that like below:

EXEC master..xp_cmdshell 'SQLCMD -E -W -Q "SET NOCOUNT ON SELECT * FROM dbname.schemaname.USER" -s "," | findstr /V /C:"-" /B > E:\export.csv'

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Export Linked Server Properties Using SQL Script

Export query result to .csv file in SQL Server 2008

Export SQL query result to CSV

Sqlcmd export data to csv using SQL Server stored procedure

Export date data from sql server 2012 using generate script

Using query export SQL Server 2008 table to Excel Sheet

Export data from Microsoft SQL Server using a query to target data

PowerShell script export SQL to CSV add delimiter

Write query to export database to csv file via Microsoft SQL Server Management Studio

Export a large CSV file in parallel to SQL server

SQL Server 2014 export CSV file issues

C# export SQL Server large tables in batches/chunks using DataReader and CSV writer

How to export large SQL Server table into a CSV file using the FileHelpers library?

Export data from CSV to sql server using asp.net C# TextFieldParser

Command line approach to SQL script export of SQL Server database

Change date format in PowerShell Export SQL to CSV script

How to export query result to csv in Oracle SQL Developer?

Export to Excel/csv by SQL query statement regularly on Windows?

Export pandas DataFrame to csv file using ArcGIS Pro script tool

export to csv powershell script using multiple foreach statements

Using OPENJSON in SQL Server Query

SQL Server Management Studio 2012 - Export all tables of database as csv

SQL Server Reporting Services CSV Report Export Option Missing

SQL Server 2014: How to include header and detail in csv export

SQL Server stored procedure to export Select Result to CSV

How to remove double quotes populating in CSV Export from SQL Server

SQL, PHP export to CSV

How to export my SQL table as a CSV fie using PYTHON

Is it possible to export every 1000 rows in a CSV from SQL using BCP?