Unfortunately in my current line of work, I’ve been pulling data from MS SQL Server. My current workflow involves remotely logging into a windows machine, and from there, using the sql server software (MS SQL Server Management Studio) to issue queries and save data. This especially sucked in that I couldn’t write in the query file where I want my output results to go. I had to manually right-click the results, copy, and paste into a txt file.
Recently I started using Oracle’s SQLDeveloper with the 3rd party plugin jTDS to skip the remote login. SQLDeveloper allowed me to log directly into the SQL Server. This did not work well in that copying the results caused issues (memory?). Also, Query Analyzer was only available if the DB was Oracle’s. The added benefit was not great.
I finally found FreeTDS by googling “linux ms sql server command line.” To install it on Mac OS X, I needed to install it via Macports (sudo port install freetds). I had issues with it initially because it could not connect with the SQL Server of interest. The problem was that I needed to specify the correct TDS version; in my case, it was version 4.2 (see this linked from this thread). You can connect using two ways:
<pre class="src src-sh"><span style="color: #eedd82;">TDSVER</span>=4.7 tsql -H myserverIP -p 1433 -U myusername -P mypassword
<pre class="src src-sh">tsql -S myserverinlist -U myusername -P mypassword
with the following in “~/.freetds.conf”
<pre class="src src-sh">[adrc]
host = myserverIP port = 1433 tds version = 4.2
For a query, remember to put go at the end of the query for it to execute (credit).
Be careful when routing input and output (“<” and “>”) as other messages from the tsql command will be present. Will post a solution when I find out.
Update 4/16/2010 – Batch output results from a query
I found out FreeTDS comes with the commands
freebcp (bcp emulation/replication) and
bsqldb. To get batch results, issue
bsqldb -U username -P password -S server.from.TDS.list -h -t '\t' -i query.sql -o query.out ## in 2nd line, has "-" characters (separate headers and data). to remove them: bsqldb -U username -P password -S server.from.TDS.list -h -t '\t' -i query.sql | sed -n '2!p' > query.out ## or use freebcp -- freebcp "$(cat query.sql)" queryout query.out -S server.from.TDS.list -U username -P password -c ## for freebcp, do not use "GO" in query
The above freebcp method does not work for me with the error
Cannot bcp with TDSVER < 5.0.
Next up is getting odbc (unixODBC to be exact) working!