I'm trying select all values if such table exists. If it doesn't exist, just leave it. I'm trying to do this only in one MYSQL code. Not with the help of python or something.
SELECT CASE WHEN (SELECT count(*)
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = '{db0}' AND TABLE_NAME = '{table0}')=0
THEN 'None' ELSE (SELECT MAX({colname}) FROM {db0}.{table0}) END;
If i inject existing table name on it, it works well. But if not , it shows the error sign that saying such table doesn't exist.(Table 'corps.060311' doesn't exist) What should I do?
CodePudding user response:
This cannot be achieved using a simple query because MySQL analyses the query as a whole before performing it: it is not a procedural language and the queries are never executed line by line. To do what you want to do without help of any other language, you must use stored procedures: https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
So the first step is to add a new FUNCTION in your database that will contain the "if table exists" part (see https://dev.mysql.com/doc/refman/8.0/en/if.html for if statements) and will return the desired value based on the schema, table, and column provided as strings in input of the function. Then you can use the FUNCTION in any query in your database.