How to run a SQL script in tsql

為{幸葍}努か 提交于 2019-12-25 06:02:30

问题


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.


回答1:


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




回答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'




回答3:


tsql -U username -P password -p 1433 > out.csv <<EOS SELECT * FROM some_table; go EOS



回答4:


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...



来源:https://stackoverflow.com/questions/17078869/how-to-run-a-sql-script-in-tsql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!