how do i pass in a command to sqsh and get the output to a file in one go?

Palace Chan picture Palace Chan · Jan 29, 2014 · Viewed 13.4k times · Source

I'm trying to set up a simple loop to periodically query a database table in bash. Normally I seem to have to do:

sqsh -s SERV -U user -P passwd -D db -L bcp_colsep=','

then within sqsh I have to type:

select * from some_table where foo=bar
\go -m bcp > /path/to/output.out

I was trying to use the -C option to sqsh to pass in the command like this:

sqsh -s SERV -U user -P passwd -D db -L bcp_colsep=',' -C 'select * from some_table where foo=bar \go -m bcp > /path/to/output.out'

but I keep getting:

Incorrect syntax near '\'.

How can I get the desired effect?

Answer

Martin Wesdorp picture Martin Wesdorp · Jan 30, 2014

When you use the -C option to pass on a SQL statement to sqsh, the \go command will be implicitly executed. To get the output in 'bcp' result style you need to set the variable 'style=bcp' using the -L parameter or use -mbcp as a commandline parameter and just redirect the output to a file, or use the sqsh -o parameter to specify a filename for output. So basically your command would look like:

sqsh -S SERV -U user -P passwd -D db -L bcp_colsep=',' -m bcp \
-C 'select * from some_table where foo=bar' > /path/to/output.out

HTH, Martin