0

I have a quite dumb client application that wants to get information from MariaDB based on a parameter. This parameter is a string that contains spaces, like 'valid parameter'. In MariaDB there is a table for each of the possible string values, and the table name is the string value after spaces have been replaced by underscores and a prefix is added. So I can perform the necessary conversion like this:

SELECT CONCAT('prefix_', REPLACE('valid parameter',' ','_'));

Now the result 'prefix_valid_parameter' is the table to query, so actually I need to fire off

SELECT * from CONCAT('prefix_', REPLACE('valid parameter',' ','_'));

but MariaDB responds with

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '('prefix_', REPLACE('valid parameter',' ','_'))' at line 1

I would have expected either the content of table 'prefix_valid_parameter' or an error stating "table 'prefix_valid_parameter' not found". How can I make the table_reference part of my SQL SELECT statement dynamic?

1 Answer 1

0

You need to use dynamic SQL:

set @sql = 'select * from [table]';

execute immediate replace(@sql, '[table]',
                          concat('prefix_', replace('valid parameter', ' ', '_'))
                         );

I should add that the need to do this perhaps suggests a flaw in your data model. If the tables have the same structure, it is better to put all the rows in a single table.

Sign up to request clarification or add additional context in comments.

4 Comments

The tables have a few common columns, but most of them are special. Hence the decision to have the in separate tables.
It works in a proper SQL client. But for crying out loud: My dumb client is Grafana, and this one neither can manipulate string values itself (github.com/grafana/grafana/issues/8259) nor can it pass the job to MariaDB using dynamic SQL (github.com/grafana/grafana/issues/8755). I am speechless.
@HiranChaudhuri . . . Perhaps you should ask another question about Grafana and dynamic SQL.
I already placed my comments on the two relevant github entries - both are referenced in my above comment. But thank you for the hint. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.