Search code examples
bashsqlcmd

Using a bash variables in sqlcmd


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

Solution

  • 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")