I need to be able to check if a column exists and if it does then I want to SELECT from it.
I am trying lots of different variations but I'm not even sure if this is possible.
Here's my latest attempt:
SELECT IF (EXISTS (SELECT `Period` AS `Period` FROM myview), `PERIOD`, IF (EXISTS (SELECT `Country` AS `COUNTRY` FROM myview),`COUNTRY` FROM myview ;
I had seen the other question on here: MySQL, Check if a column exists in a table with SQL
But I still struggle with the if statement. I can check to see if the column exists using the answer in the question above. But my question is - how to execute a select statement from that column if the result is found to be true.
The answer below indicates that I should use the BEGIN and END statement and this makes sense. However, my query complains at the first line. It says 'unexpected IF' - can anybody confirm if this is the right syntax fro MYSQL?
if( exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME = 'view_name' AND COLUMN_NAME = 'column_name') ) begin SELECT `column_name` FROM `view_name` end
Thanks in advance.