I have a variable whose value is set by the user each time the person runs a query. I am running this script in python which then makes a call to a postgres database. I am hoping to first assigning a value to the variable in one piece of sql code and then I am hoping to call that variable in a second piece of sql code.
Here is my current code:
First my code to set the postgres variable:
sql_stateVar=("""
tempState VARCHAR:= %s
"""
,(stateVar,))
cur.execute(*sql_stateVar)
Then with this variable set in postgres, I am going to call this stored variable:
sqlquery=("""
SELECT UPPER(b.state) AS state,
FROM opentable_full b
WHERE UPPER(b.state)=UPPER(tempState)
GROUP BY UPPER(b.state)
""")
Then I have the following code:
outputquery = "COPY({0}) TO STDOUT WITH CSV HEADER".format(sqlquery)
with open('resultsfile', 'w') as f:
cur.copy_expert(outputquery, file=f)
I have seen several answers regarding the limitations of setting variables in postgres, but as I am new to postgres, I am not sure if these answers are what I need.
For example:
Is there a way to define a named constant in a PostgreSQL query?
AND
How to declare local variables in postgresql?