0

I have been tasked with replacing ISQL in a lot of our bash scripts with sqlcmd. ISQL allows piping a variable in it's execution. An example would be:

    SQL_STATEMENT="SELECT TOP 1 SYS_USER_NAME FROM SYS_USER"
    echo $SQL_STATEMENT | isql -b -d, $DSN $DBUID $DBPWD >> setupdb_test.txt

From what I can tell this is not viable in sqlcmd. How can I do this? What flags does sqlcmd have to allow this to happen?

Here is what I have tried and have had a good result BUT I really do not want to create the file sql_command.sql every time a particular script runs:

    echo "SELECT TOP 1 SYS_USER_NAME FROM SYS_USER" > sql_command.sql
    sqlcmd -S $DB -U $DBUID -P $DBPWD -d $DSN -i sql_command.sql >> setupdb_test.txt
3
  • have you tried this? export SQL_COMMAND="SELECT TOP 1 SYS_USER_NAME FROM SYS_USER"; sqlcmd -S $DB -U $DBUID -P $DBPWD -d $DSN -i $SQL_COMMAND >> setupdb_test.txt Commented Jul 10, 2019 at 18:06
  • Unfortunately this did not work for me. I get an error of: Sqlcmd: 'SELECT': Invalid filename. Commented Jul 10, 2019 at 18:55
  • ok. the SQL_COMMAND contain space, so the $SQL_COMMAND must be quoted. Like this: sqlcmd -S $DB -U $DBUID -P $DBPWD -d $DSN -i "$SQL_COMMAND" >> setupdb_test.txt Commented Jul 11, 2019 at 8:05

1 Answer 1

2

Programs originating on Windows can be picky about how they handle non-regular files and I don't have the opportunity to test, but you can try the typical Unix tricks for providing a "file" with data from an echo.

Either /dev/stdin:

echo "SELECT TOP 1 SYS_USER_NAME FROM SYS_USER" | sqlcmd -S "$DB" -U "$DBUID" -P "$DBPWD" -d "$DSN" -i /dev/stdin

or process substitution:

sqlcmd -S "$DB" -U "$DBUID" -P "$DBPWD" -d "$DSN" -i <(echo "SELECT TOP 1 SYS_USER_NAME FROM SYS_USER")
Sign up to request clarification or add additional context in comments.

1 Comment

This works, I also tried SQL_COMMAND="SELECT TOP 1 SYS_USER_NAME FROM SYS_USER" echo $SQL_COMMAND | sqlcmd -S $DB -U $DBUID -P $DBPWD -d $DSN -i /dev/stdin >> setupdb_test.txt and this works as well. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.