I can quite easily dump data into a text file such as:
sqlcmd -S myServer -d myDB -E -Q \"select col1, col2, col3 from SomeTable\"
-o \"MyData.txt\"
>
Usually sqlcmd
comes with bcp utility (as part of mssql-tools
) which exports into CSV by default.
Usage:
bcp {dbtable | query} {in | out | queryout | format} datafile
For example:
bcp.exe MyTable out data.csv
To dump all tables into corresponding CSV files, here is the Bash script:
#!/usr/bin/env bash
# Script to dump all tables from SQL Server into CSV files via bcp.
# @file: bcp-dump.sh
server="sql.example.com" # Change this.
user="USER" # Change this.
pass="PASS" # Change this.
dbname="DBNAME" # Change this.
creds="-S '$server' -U '$user' -P '$pass' -d '$dbname'"
sqlcmd $creds -Q 'SELECT * FROM sysobjects sobjects' > objects.lst
sqlcmd $creds -Q 'SELECT * FROM information_schema.routines' > routines.lst
sqlcmd $creds -Q 'sp_tables' | tail -n +3 | head -n -2 > sp_tables.lst
sqlcmd $creds -Q 'SELECT name FROM sysobjects sobjects WHERE xtype = "U"' | tail -n +3 | head -n -2 > tables.lst
for table in $( $table.desc && \
bcp $table out $table.csv -S $server -U $user -P $pass -d $dbname -c
done