83

I want to: Export table from sql server database to a comma delimited csv file without using sql Server import export wizard

I want to do it using a query because I want to use the query in automation

Is it possible? I searched for that and didn't find a good answer

Blachshma
  • 17,097
  • 4
  • 58
  • 72
Abdalwhab Bakheet
  • 1,133
  • 2
  • 11
  • 17
  • 3
    Yes it is possible, you can use C#, php and almost any other programming language... [What have you tried?](http://whathaveyoutried.com) – Blachshma Jan 08 '13 at 10:18
  • Related post - [Export query result to .csv file in SQL Server 2008](https://stackoverflow.com/q/3169220/465053) – RBT Mar 18 '19 at 09:53

10 Answers10

148

Some ideas:

From SQL Server Management Studio

 1. Run a SELECT statement to filter your data
 2. Click on the top-left corner to select all rows
 3. Right-click to copy all the selected
 4. Paste the copied content on Microsoft Excel
 5. Save as CSV

Using SQLCMD (Command Prompt)

Example:

From the command prompt, you can run the query and export it to a file:

sqlcmd -S . -d DatabaseName -E -s, -W -Q "SELECT * FROM TableName" > C:\Test.csv

Do not quote separator use just -s, and not quotes -s',' unless you want to set quote as separator.

More information here: ExcelSQLServer

Notes:

  • This approach will have the "Rows affected" information in the bottom of the file, but you can get rid of this by using the "SET NOCOUNT ON" in the query itself.

  • You may run a stored procedure instead of the actual query (e.g. "EXEC Database.dbo.StoredProcedure")

  • You can use any programming language or even a batch file to automate this

Using BCP (Command Prompt)

Example:

bcp "SELECT * FROM Database.dbo.Table" queryout C:\Test.csv -c -t',' -T -S .\SQLEXPRESS

It is important to quote the comma separator as -t',' vs just -t,

More information here: bcp Utility

Notes:

  • As per when using SQLCMD, you can run stored procedures instead of the actual queries
  • You can use any programming language or a batch file to automate this
starball
  • 20,030
  • 7
  • 43
  • 238
priboyd
  • 1,917
  • 2
  • 12
  • 19
  • 2
    That first suggestion is just so wonderfully direct. :-) The others will work varyingly well depending on commas and line breaks in the data (both of which are valid in proper CSV files, properly quoted). – T.J. Crowder Nov 11 '15 at 13:07
  • The first suggestion dumps data without column names (SQL Server 2014). Is there a handy way to include them? – Przemyslaw Remin Aug 25 '17 at 16:41
  • @PrzemyslawRemin - Ensure Results To Grid is selected, run the query, and in the query results grid, right-click on the top-left blank corner cell and select "Copy with Headers". It gives a tab-separated output that can be easily pasted into excel. – dunc Dec 22 '17 at 21:30
  • dunc, the question asks for automation solutions. – FreeText Jun 01 '18 at 21:05
  • 1
    Does not work. I tried to the first approach, and it does not produce valid CSV output. In particular, it does not escape the separator characters which may naturally occur in the data. It might work for some particular case if you are able to discover a separator character that does not occur in the data and is also accepted by sqlcmd. – Atte Juvonen May 05 '21 at 13:35
8

Here is an option I found to export to Excel (can be modified for CSV I believe)

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=D:\testing.xls;', 
'SELECT * FROM [SheetName$]') select * from SQLServerTable
Faiz
  • 5,331
  • 10
  • 45
  • 57
  • I got `SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', search for 'Ad Hoc Distributed Queries' in SQL Server Books Online.` – xpt Jun 11 '15 at 15:48
  • 2
    You have all the information you needed to fix the error in the message itself. Just enable 'Ad Hoc Distributed Queries'. – Faiz Jun 12 '15 at 10:59
  • 2
    , when I provide an answer, I'll give a complete one, and over 99% people in stackexchange do so as well. The purpose of stackexchange is to avoid people hunting down answers from all over the web. Apparently, not everyone see the importance of this. – xpt Jun 12 '15 at 13:47
  • 5
    Here is the answer: http://stackoverflow.com/a/14544245/82961 But please put some effort before asking someone else to do it for you. Use SO when you cannot figure out how to do it rather than when you are not interested in finding out how to do it. That will only make you a lazy programmer than a good one.. No offense meant.. Also please grow the habit of reading the error message completely, most of the time all the clues you need are there. – Faiz Jun 12 '15 at 13:54
  • 1
    Apparently, we disagree on the importance of providing complete answers, but I can live with that -- agree to disagree. – xpt Jun 12 '15 at 14:01
  • I Get Ad hoc access to OLE DB provider 'Microsoft.Jet.OLEDB.4.0' has been denied. You must access this provider through a linked server. – Ben DeMott Apr 18 '17 at 18:35
8

You can also use following Node.js module to do it with ease:

https://www.npmjs.com/package/mssql-to-csv

var mssqlExport = require('mssql-to-csv')

    // All config options supported by https://www.npmjs.com/package/mssql 
    var dbconfig = {
        user: 'username',
        password: 'pass',
        server: 'servername',
        database: 'dbname',
        requestTimeout: 320000,
        pool: {
            max: 20,
            min: 12,
            idleTimeoutMillis: 30000
        }
    };

    var options = {
        ignoreList: ["sysdiagrams"], // tables to ignore 
        tables: [],                  // empty to export all the tables 
        outputDirectory: 'somedir',
        log: true
    };

    mssqlExport(dbconfig, options).then(function(){
        console.log("All done successfully!");
        process.exit(0);
    }).catch(function(err){
        console.log(err.toString());
        process.exit(-1);
   });
adnan kamili
  • 8,967
  • 7
  • 65
  • 125
5

You don't need to go through hoops with SSMS or programming languages.

Run a PowerShell prompt as administrator, then:

Install-Module -Name SqlServer

Once installed you can export any table to CSV like this:

Invoke-Sqlcmd -Query "SELECT * FROM [mydatabase].[dbo].[mytable]" -ServerInstance "MYSQLSERVER" | Export-Csv -Path "c:\temp\output.csv" -NoTypeInformation

You can put that in a .PS1 script and execute it however you like.

Alan B
  • 4,086
  • 24
  • 33
  • Powershell is a really good tool for automation in the MS environment. Your solution is also quite elegant. Nicely done on finding a relevant answer to a 9 year old question! – kiltannen Feb 08 '22 at 20:51
4
rsubmit;
options missing=0;
ods listing close;
ods csv file='\\FILE_PATH_and_Name_of_report.csv';

proc sql;
SELECT *
FROM `YOUR_FINAL_TABLE_NAME';
quit;
ods csv close;

endrsubmit;
John
  • 49
  • 1
4

From SQL Server Management Studio

Right click the table you want to export and select "Select All Rows"

Right click the results window and select "Save Results As..."

Giovanni S
  • 2,050
  • 18
  • 33
2

In SQL Server Management Studio query window

  1. Select All result set values
  2. Right Click and Select "Save Results As"

Table Content to CSV

  1. Save as CSV file
Jignesh Variya
  • 1,869
  • 16
  • 12
  • The only problem with this method is that it produces 3 lines at the end of the CSV file with text containing the Execution time. So you will need to edit the csv file. If its too large use Notepad++. I will figure out how to eliminate the last 3 lines of text. – Clark Vera Jul 09 '21 at 16:53
  • Notepad++ can open files up to 2GB, if you're going over that limit I would suggest that CSV is not the format you should be using. – Alan B Sep 02 '21 at 07:45
1

I wrote a small tool that does just that. Code is available on github.

To dump the results of one (or more) SQL queries to one (or more) CSV files:

java -jar sql_dumper.jar /path/sql/files/ /path/out/ user pass jdbcString

Cheers.

Boern
  • 7,233
  • 5
  • 55
  • 86
0

And when you want all tables for some reason ?

You can generate these commands in SSMS:

SELECT 
CONCAT('sqlcmd -S ',
'Your(local?)SERVERhere'
,' -d',
'YourDB'
,' -E -s, -W -Q "SELECT * FROM ',
TABLE_NAME,
'" >',
TABLE_NAME,
'.csv') FROM INFORMATION_SCHEMA.TABLES

And get again rows like this

sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table1" >table1.csv
sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table2" >table2.csv
...

There is also option to use better TAB as delimiter, but it would need a strange Unicode character - using Alt+9 in CMD, it came like this ○ (Unicode CB25), but works only by copy/paste to command line not in batch.

Jan
  • 2,178
  • 3
  • 14
  • 26
-1

Dead horse perhaps, but a while back I was trying to do the same and came across a script to create a STP that tried to do what I was looking for, but it had a few quirks that needed some attention. In an attempt to track down where I found the script to post an update, I came across this thread and it seemed like a good spot to share it.

This STP (Which for the most part I take no credit for, and I can't find the site I found it on), takes a schema name, table name, and Y or N [to include or exclude headers] as input parameters and queries the supplied table, outputting each row in comma-separated, quoted, csv format.

I've made numerous fixes/changes to the original script, but the bones of it are from the OP, whoever that was.

Here is the script:

IF OBJECT_ID('get_csvFormat', 'P') IS NOT NULL
    DROP PROCEDURE get_csvFormat
GO

CREATE PROCEDURE get_csvFormat(@schemaname VARCHAR(20), @tablename VARCHAR(30),@header char(1))
AS
BEGIN
    IF ISNULL(@tablename, '') = ''
    BEGIN
        PRINT('NO TABLE NAME SUPPLIED, UNABLE TO CONTINUE')
        RETURN
    END
    ELSE
    BEGIN
        DECLARE @cols VARCHAR(MAX), @sqlstrs VARCHAR(MAX), @heading VARCHAR(MAX), @schemaid int

        --if no schemaname provided, default to dbo
        IF ISNULL(@schemaname, '') = ''
            SELECT @schemaname = 'dbo'

        --if no header provided, default to Y
        IF ISNULL(@header, '') = ''
            SELECT @header = 'Y'

        SELECT @schemaid = (SELECT schema_id FROM sys.schemas WHERE [name] = @schemaname)
        SELECT 
        @cols = (
            SELECT ' , CAST([', b.name + '] AS VARCHAR(50)) '  
            FROM sys.objects a 
            INNER JOIN sys.columns b ON a.object_id=b.object_id 
            WHERE a.name = @tablename AND a.schema_id = @schemaid
            FOR XML PATH('')
        ),
        @heading = (
            SELECT ',"' + b.name + '"' FROM sys.objects a 
            INNER JOIN sys.columns b ON a.object_id=b.object_id 
            WHERE a.name= @tablename AND a.schema_id = @schemaid
            FOR XML PATH('')
        )

        SET @tablename = @schemaname + '.' + @tablename
        SET @heading =  'SELECT ''' + right(@heading,len(@heading)-1) + ''' AS CSV, 0 AS Sort'  + CHAR(13)
        SET @cols =  '''"'',' + replace(right(@cols,len(@cols)-1),',', ',''","'',') + ',''"''' + CHAR(13)

        IF @header = 'Y'
            SET @sqlstrs =  'SELECT CSV FROM (' + CHAR(13) + @heading + ' UNION SELECT CONCAT(' + @cols + ') CSV, 1 AS Sort FROM ' + @tablename + CHAR(13) + ') X ORDER BY Sort, CSV ASC'
        ELSE
            SET @sqlstrs =  'SELECT CONCAT(' + @cols + ') CSV FROM ' + @tablename 

        IF @schemaid IS NOT NULL 
            EXEC(@sqlstrs)
        ELSE 
            PRINT('SCHEMA DOES NOT EXIST')
    END
END

GO

--------------------------------------

--EXEC get_csvFormat @schemaname='dbo', @tablename='TradeUnion', @header='Y'
svenGUTT
  • 399
  • 4
  • 11