35

I have a database in SQL Server with a lot of tables and wish to export all tables in csv format. From a very similar question asked previously - Export from SQL Server 2012 to .CSV through Management Studio

Right click on your database in management studio and choose Tasks -> Export Data...

Follow a wizard, and in destination part choose 'Flat File Destination'. Type your file name and choose your options.

What I want is the capability to export all tables at once. The SQL Server Import and Export Wizard only permits one table at a time. This is pretty cumbersome, if you have a very big database. I think a simpler solution might involve writing a query, but not sure.

Community
  • 1
  • 1
Ashwini Khare
  • 1,445
  • 3
  • 17
  • 36
  • 1
    In theory you can export as many tables as you like to an .XLS format, and from there it would be a snip to save them as multiple CSVs. In practice... I'd hate to try more than about 10 tables into a single workbook, if they've got any significant amount of data in them. – Mike K Jun 11 '15 at 21:22

5 Answers5

72

The export wizard allows only one at a time. I used the powershell script to export all my tables into csv. Please try this if it helps you.

$server = "SERVERNAME\INSTANCE"
$database = "DATABASE_NAME"
$tablequery = "SELECT schemas.name as schemaName, tables.name as tableName from sys.tables inner join sys.schemas ON tables.schema_id = schemas.schema_id"

#Delcare Connection Variables
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $tablequery
$command.Connection = $connection

#Load up the Tables in a dataset
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()



# Loop through all tables and export a CSV of the Table Data
foreach ($Row in $DataSet.Tables[0].Rows)
{
    $queryData = "SELECT * FROM [$($Row[0])].[$($Row[1])]"

    #Specify the output location of your dump file
    $extractFile = "C:\mssql\export\$($Row[0])_$($Row[1]).csv"

    $command.CommandText = $queryData
    $command.Connection = $connection

    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $command
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $connection.Close()

    $DataSet.Tables[0]  | Export-Csv $extractFile -NoTypeInformation
}

Thanks

Giffyguy
  • 17,946
  • 30
  • 81
  • 147
sree
  • 1,510
  • 1
  • 18
  • 32
  • 3
    Thank you for this. Had some trouble with the SERVERNAME\INSTANCE --- What worked me was just to have the SERVERNAME there and then making sure I had the folders c:\mssql\export folders created as well. Cheers. – bDreadz May 02 '17 at 18:22
  • 1
    Is it easy enough to append the table name in each of the exported files with the number of rows in the table? I'm trying to use this for comparative purposes and that would make things a lot easier for me. Great script by the way! – tonyyeb Aug 31 '17 at 09:29
  • 1
    One more improvement in this script can be addition of "-encoding "unicode" " parameter on Export-Csv line to support international languages. – Furqan Hameedi Sep 06 '17 at 06:18
  • 3
    A very useful script. One caveat though... It will only work well for not too big tables. After a while, memory will get saturated, I guess mostly by the last line. If anyone has a more memory safe version of this script, that could be very useful. – KookieMonster Dec 18 '17 at 08:22
  • Thank you for this script! It proved helpful for me for a database that had to be "downgraded" - backed up on SQL 2016 but the other person has only SQL 2014. Thanks again. – jrdevdba Nov 05 '20 at 16:01
  • Can someone please tell me how this script was able to get permission to run the necessary queries? It worked for me, but it never asked for a DB user or Password. Is it using my windows credentials? If so how can I have it use a specific user's credentials? – Tan Rezaei Apr 17 '21 at 02:47
  • Thanks! If you want to make sure it can be opened directly by Excel just double-clicking on it, in column mode, with support for any language characters, add this to the Export-Csv command: -Encoding "unicode" -Delimiter "`t" (equivalent to this UI https://stackoverflow.com/a/36018426/403671) – Simon Mourier May 05 '21 at 10:10
16

Instead of clicking Export Data, choose Generate Scripts. Select the tables you want, click next and click the Advanced button. The last option under General is Types of data to script. Chose Schema and data or just Data.

JamieD77
  • 13,358
  • 1
  • 15
  • 25
  • 5
    Even if I select "Data" only in last option, the exported files are in Microsoft SQL Server Query File format. It's not text, or csv, which is what I want. Any workaround for that? – Ashwini Khare Jun 11 '15 at 21:18
  • In SS2016 I can't find this option. Generate Scripts only lets me choose database objects but doesn't give option to choose data from tables. – EAmez Mar 11 '19 at 05:53
  • 1
    @EAmez I can still see the option. After you choose options, the `Set Scription Options` tab has an `Advanced` button for more options. Click that and you should see `Types of data to script` as the last option under General. It defaults to Schema only but you can choose Data only or Schema and data. – JamieD77 Mar 11 '19 at 14:46
  • @JamieD77, you were right. I had missed the button "Advanced" in that step of scripting database. Thank you. – EAmez Mar 29 '19 at 08:06
  • with MSSQL Studio 18 I keep getting .sql files, both when selecting 'Data only' or 'Schema and Date' :/ how can i fix this? I need the csv's – user1805743 Apr 17 '20 at 16:20
5

The answer by sree is great. For my db, because there are multiple schemas, I changed this:

$tablequery = "SELECT schemas.name as schemaName, tables.name as tableName from sys.tables inner join sys.schemas ON tables.schema_id = schemas.schema_id"

and then also

$queryData = "SELECT * FROM [$($Row[0])].[$($Row[1])]"

#Specify the output location of your dump file
$extractFile = "C:\mssql\export\$($Row[0])_$($Row[1]).csv"
NP3
  • 933
  • 1
  • 6
  • 15
  • This is extremely useful. Most databases have multiple schemas, and it's important to account for this in the script. – Giffyguy Nov 18 '19 at 22:50
2

Comment on @annem-srinivas solution: If you use schemas other than the default (dbo), change the following in his script:

$tablequery = "SELECT schemas.name as schemaName, tables.name AS tableName from sys.tables INNER JOIN sys.schemas ON schemas.schema_id
= tables.schema_id ORDER BY schemas.name, tables.name"

and

$queryData = "SELECT * FROM [$($Row[0])].[$($Row[1])]"
$extractFile = "C:\temp\export\$($Row[0]).$($Row[1]).csv"
w5ar
  • 31
  • 2
0

1st Way

You can replicate the schema to a temp database and then use that database to export all tables (along with column names).

Steps:

1) First, create a script for all the tables:
Tasks->Generate Scripts->all tables->single sql file

2) Create a dummy database and run this script.

3) right click on the dummy database and select tasks->export data-> select source data->select destination as Microsoft Excel and give its path->Execute

You'll get a single spreadsheet with all the tables and its columns.

2nd Way

Execute below query, it'll give all table names in 1st column along with corresponding column names in 2nd column of result.

select t.name ,c.name from sys.columns c
inner join sys.tables t
on t.object_id = c.object_id
order by t.name

Copy this result and paste it in CSV.

GorvGoyl
  • 27,835
  • 20
  • 141
  • 143
  • Unfortunately the Excel export has never actually worked for me. There is ALWAYS a massive slew of errors from too many rows (seems to cap at 2^16 when excel can hold 2^20) to conversion errors. – Douglas Gaskell Dec 07 '18 at 19:17