A
A
Alexey Ukolov2014-12-18 17:38:29
MySQL
Alexey Ukolov, 2014-12-18 17:38:29

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;

But the use of dynamic expressions in triggers is prohibited.
There is a variant to receive all values ​​of all properties for object and through hell from conditions to carry out one of requests. Something like this (this is a simplified pseudo-code):
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)

Is there a more elegant way to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vapaamies, 2014-12-27
@vapaamies

Make views and instead of -triggers fail? Does MySQL instead of -triggers support?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question