Pass in SQL query the table name as parameter

A possible solution for this question is here: https://stackoverflow.com/a/6223961/12343395 It will probably work with a lot of work around. But I have stored my table names in string format and want to call them as needed. I am using Pandas read_sql_query. So as in params, I am passing, the table name and a few parameters in the WHERE section. The WHERE section is fine, since the parameters are originally strings. But in the FROM section, I really want the schema.table as a non-string. Here is a snippet.

SELECT "rainfall(mm)","tmin(C)","tmax(C)","TimeStamp"
FROM crop_tables[choose_crop][0]
WHERE "District_Name" = %s AND "Season" = %s
ORDER BY "TimeStamp" ASC

where crop_tables[choose_crop][0] is 'sagita_historic.soyabean_daily_analyses' in this case. But FROM will throw an error since it doesn't accept strings. So in essence, I wish to strip the 'sagita_historic.soyabean_daily_analyses' as a non-string. Is it possible to do so? Thank you.

1 answer

  • answered 2019-11-08 14:00 prp

    Not sure I fully understand but maybe this will do?

    SELECT "rainfall(mm)","tmin(C)","tmax(C)","TimeStamp"
    FROM f"{crop_tables[choose_crop][0]}"
    WHERE "District_Name" = %s AND "Season" = %s
    ORDER BY "TimeStamp" ASC