简体   繁体   中英

Bash script to run SQL query and return result to variable

I am running this bash script in order to connect to a PostgreSQL database, run some query, and simply check whether it returns an empty result or not. Then, I want to print out whether any rows were returned.

#!/bin/sh
DATABASE=dbname
USERNAME=user
HOSTNAME=somehost.com
export PGPASSWORD=password

queryResult () {
psql -h $HOSTNAME -U $USERNAME -d $DATABASE <<SQL
SELECT * FROM myTable WHERE valueA > 5.0 OR valueB > 5.0;
IF @@ROWCOUNT > 0 THEN 1 ELSE 0;
SQL
}

valuesFound=$(queryResult)

echo $valuesFound

There are two issues I'm having with this:

1) It stores the result of the first query ( SELECT * FROM myTable... ) into valuesFound and prints it, and I don't want that. All I care about is whether the IF statement returns 1 or 0.

2) The second query ( IF @@ROWCOUNT... ) throws a syntax error: Syntax error at or near IF

I think that your script can be simplified by moving the logic to a unique statement:

queryResult () {
    psql -h $HOSTNAME -U $USERNAME -d $DATABASE <<SQL
        SELECT CASE WHEN COUNT(*) = 0 THEN 0 ELSE 1 END
        FROM myTable 
        WHERE valueA > 5.0 OR valueB > 5.0;
    SQL
}

Or better yet, using EXISTS to avoid a potentially expensive aggregation:

queryResult () {
    psql -h $HOSTNAME -U $USERNAME -d $DATABASE <<SQL
        SELECT CASE WHEN EXISTS (
            SELECT 1 FROM myTable WHERE valueA > 5.0 OR valueB > 5.0
        ) THEN 1 ELSE 0 END;
    SQL
}

IF @@ROWCOUNT > 0 THEN 1 ELSE 0; is T-SQL feature which PostgreSQL does not support.

The general solution could be:

myvar=$(psql -c "<SQL query>")
if [ -z "$myvar" ]; then
    # Do something when no data found
else
    # Data found, handle it
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM