I have a DB named catalog DB which contains 4 tables in that one is the Customers table which has a list of customers and their alias. I want to insert a row in a table (tableA) available in all customer Databases. This has to happen on INSERT in a table (table_in_catalogDB) in catalog DB. Each customer has the same set of tables which has their own data.
CREATE TRIGGER catalogDB.insertInMultipleDatabases AFTER INSERT ON catalogDB.table_in_catalogDB
FOR EACH ROW
BEGIN
DECLARE maxCustId INT;
DECLARE minCustId INT;
DECLARE loopCounter INT; // For looping over all the customers
DECLARE cust_name VARCHAR(100);
SELECT min(custId) AS minCustId, max(custId) AS maxCustId FROM Customers;
SET loopCounter = minCustId;
WHILE loopCounter <= maxCustId DO // Using loopCounter here as the custId's are
SET cust_name = (SELECT alias FROM Customers WHERE custId = loopCounter);
SET dbName = CONCAT(cust_name, '.tableA'); //tableA is available for all customers
INSERT INTO dbName (column names) VALUES (from new.column); // This query has to be dynamic because alias name is concatenated with the table name and then to be used in the INSERT statement
SET loopCounter = loopCounter + 1;
END WHILE;
END
I tried using the cursor and prepared statement in this trigger and then understood that triggers cannot contain prepared statements. I need to use triggers.