I understand that prepared statements aren’t allowed within a trigger, but I can’t see how else I can do what I want, so any alternatives/workarounds would be greatly appreciated.
DELIMITER $$
CREATE TRIGGER trigger1 after INSERT on table1
FOR EACH ROW
begin
DECLARE a varchar(30);
DECLARE b varchar(30);
DECLARE c varchar(30);
DECLARE d varchar(30);
SET a = new.Col1;
SET b = new.Col2;
SET c = (select Col4 from table2 where Col3=new.Col3);
SET d = concat('select ',a,' from table3 where yq=',c,' and xz=',b);
insert into table4 values (d);
end
$$
DELIMITER;
So what is happening: a row is inserted and 3 values are taken from that row, Col1,Col2, and new.Col3.
new.Col3 is used to get a row from a different table, which is then used along with Col2 to search the 3rd table where the value I need is.
Col1 is the problem because it is supposed to be a dynamically generated column name for d but this doesn’t work.
So obviously at the moment all I am getting back is a string of the select statement in d which is what I expect, but I cant execute the statement because that is not allowed.
So how can I get that dynamically generated column name in to the select statement?
Table 1
Col1 | Col2 | Col3
c | d | x
a | e | y
b | e | z
b | f | x
Table 2
Col3 | Col4
x | 1
y | 2
z | 3
Table3
a | b | c | xz | yq
1a | 1b | 1c | d | 1
2a | 2b | 2c | d | 2
3a | 3b | 3c | d | 3
4a | 4b | 4c | e | 1
5a | 5b | 5c | e | 2
6a | 6b | 6c | e | 3
7a | 7b | 7c | f | 1
8a | 8b | 8c | f | 2
9a | 9b | 9c | f | 3
The result I want is from 1a-9c.
I have considered changing the table schema so that the column name in the trigger can be fixed, but that would be a last resort since it would cause issues for other bits of code.
You will have to abandon the idea of prepared statements and dynamic SQL altogether and just painfully do some
IF..THENstatements: