I have a trigger containing this:
SET v1 = CONCAT_WS(',',NEW.ID, NEW.Name, NEW.Type, NEW.Value);
Can this be simplified into something like this to include the entire new row?:
SET v1 = CONCAT_WS(',',NEW.*);
(I’ve tried variations of the above however they causes syntax errors)
Thanks
No, there’s no easy way to do this. You have to reference each column.
The only real workaround is to use the table metadata to help you generate the statement you want, and then include that statement in your procedure.
You wouldn’t want to do this dynamically in the TRIGGER, even if it were possible.
That should get you a string that looks like:
And you can paste that into your trigger body. (Of course you could extend the CONCAT to generate the whole line.)
The downside is that when new columns are added to the table, those won’t get automatically included; that will require a change in the trigger. If a column gets dropped or renamed, your trigger will start throwing exceptions; again requiring a fix to the trigger.
UPDATE
Q:How can I convert this string into a MySQL query?
I wouldn’t convert that to a query. I would just use that as static line of code (with no double quotes) in the body of your trigger, just like the original statement you had in your TRIGGER.
(It wasn’t clear what you intended to do with that string.)
If you are trying to create a SELECT statement, you could try removing that semicolon from the end of the string, and prepending a SELECT keyword on it. But I don’t think the NEW. references to the column values of the current row will be recognized in that context. That might happen, but you’d need to test.
If I needed to do something like that, I would do it using user variables,
It’s not at all clear to me what you are going to do with the result set returned by a query like. If you are attempting to audit changes to the table, the normative pattern is to run an INSERT of the column values into an changelog table,
It really depends on what you are trying to accomplish.