Answer the question
In order to leave comments, you need to log in
How to update a table from a trigger if the column name is stored in a variable?
The task is this:
There is a table in which property values are stored as object_id , property_id , value .
When I insert a new value and update an existing one, I want to automatically fill in another table - object_id , property_1 , property_2 , etc.
Tried doing it like this:
DECLARE code VARCHAR(50);
# Здесь определяем code
PREPARE update_statement FROM 'UPDATE aggregated SET ? = ? WHERE id = ?';
SET @column = code;
SET @value = NEW.value;
SET @id = NEW.id;
EXECUTE update_statement USING @column, @value @id;
DEALLOCATE PREPARE update_statement;
SELECT value INTO name_value FROM objects WHERE id = NEW.id AND property_code = 'name';
SELECT value INTO some_field_value FROM objects WHERE id = NEW.id AND property_code = 'some_field';
SELECT value INTO some_other_field_value FROM objects WHERE id = NEW.id AND property_code = 'some_other_field';
switch code
case name
name_value = NEW.value
case some_field
some_field_value = NEW.value
case some_other_field
some_other_field_value = NEW.value
UPDATE aggregated (name, some_field, some_other_field) VALUES (name_value, some_field_value, some_other_field_value)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question