user1156596 user1156596 - 22 days ago 8
SQL Question

Concatenating user-defined variables in mysql

I have three user defined variables, and have only figured out how to concatenate at most, two at a time by performing the following query.

SET @sql := (CONCAT(@sql_q1, ' UNION ', @sql_med));


I also want to concatenate my other user-defined variable, @sql_q3, Such that @sql stores @sql_q1, @sql_med and @sql_q3.

Is there a way in which I can concatenate three user defined variables similar to above?

All three variables use the same data from the same table. So joining them isn't an issue, as I can mix and match two variables at a time by using my union line above.

Thank you for your help!

Answer

Use CONCAT_WS():

SET @sql := CONCAT_WS(' UNION ', @sql_q1, @sql_med, @sql_q3);

Note: I would recommend that you use UNION ALL rather than UNION.

Also, if one or more of the variables are NULL, then it string will still look okay.

Comments