0

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!

4
  • Can you give an example of the value of each variable? Commented Nov 11, 2016 at 11:34
  • sql_q1 holds 58, sql_med holds 116 and sql_q3 holds 172. They are the lower quartile, median and upper quartile from a column that has values from 1 to 230. Commented Nov 11, 2016 at 11:37
  • 1
    Try: SET @`sql_q1` := 'SELECT 58', @`sql_med` := 'SELECT 116', @`sql_q3` := 'SELECT 172'; SET @`sql` := (CONCAT(@`sql_q1`, ' `quartile` UNION ', @`sql_med`, ' UNION ', @`sql_q3`)); Commented Nov 11, 2016 at 11:43
  • 1
    Your solution works well, but Gordon's will get the vote for neatness. Thank you for your help Commented Nov 11, 2016 at 11:52

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.