Question

I'm using tsql (installed with FreeTDS) and I'm wondering if there's a way to run a SQL script in tsql from the command line and get the result in a text file.

For example, in psql I can do:

psql -U username -C "COPY 'SELECT * FROM some_table' to 'out.csv' with csv header"

Or:

psql -U username -C "\i script.sql"

And in script.sql do:

\o out.csv
SELECT * FROM  some_table;

Is there a way for doing this in tsql? I have read the linux man page and search everywhere but I just don't find a way.

Was it helpful?

Solution 2

I really didn't find how to do this and I'm starting to thinks it just can't be done in tsql. However I solved for my specific problem redirecting the stdin and stdout. I use a bash script like this:

tsql connection parameters < tsql_input.sql > tsql_output.csv
lines=`cat tsql_output.csv | wc -l`

# The output includes the header info of tsql and the "(n number of rows)" message
# so I use a combination of head and tail to select the lines I need
headvar=$((lines-2))
tailvar=$((lines-8))

head -$headvar tsql_output.csv | tail -$tailvar tsql_output.csv > new_output_file.csv

And that saves just the query result on 'new_output_file.csv'

OTHER TIPS

I think, you can try "bsqldb", see http://linux.die.net/man/1/bsqldb

freebcp "select * from mytable where a=b" queryout sample.csv -U anoop -P mypassword -S hostname.com -D dbname -t , -c

This command woks like a charm. Kudos to FreeTDS...

tsql -U username -P password -p 1433 > out.csv <<EOS SELECT * FROM some_table; go EOS
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top