1

I am creating a MySQL dump file, that needs to run with multiple databases. The structure is almost like this :

SET @parent_database = 'db_name';
CREATE OR REPLACE VIEW t_colours AS
   SELECT `key_name`, `value`
   FROM @parent_database. `colours` as COLOURS WHERE 1;

When I run this query next time, my plan is to only change the variable parent_database.

Is this possible?

Everytime now I run this, I receive an error :

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@parent_database.`colours` as COLOURS WHERE 1' at line 1

Any way to make this happen?

There are many more views to create.

2
  • you can't use var for tables or columns name Commented Jun 5, 2017 at 9:31
  • You can't get data from the database without making connection to the respected database so it won't work; Commented Jun 5, 2017 at 9:48

1 Answer 1

1

When you execute the queries the mysql thinks of table names as objects and not as string, and hence this would not work as you would expect.

However, there is a way out and you could use something similar to below snippet.

SET @parent_database = 'db_name';
SET @q = CONCAT('CREATE OR REPLACE VIEW t_colours AS SELECT `key_name`,`value` FROM', @parent_database, '.`colours` as COLOURS WHERE 1;');
PREPARE stmt FROM @q; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;
Sign up to request clarification or add additional context in comments.

Comments

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.