1

Having an input parameter, for example num = 3, I want to create a string in MySQL, concatenated by ','.

In Python it would look like this:

num = 3

string = ['target_table']
for i in range(num):
    string.append('hub_hid_column_' + str(i))
    string.append('hub_hid_column_name_' + str(i))

print(','.join(string))

At the end i want to have the following output: target_table,hub_hid_column_0,hub_hid_column_name_0,hub_hid_column_1,hub_hid_column_name_1,hub_hid_column_2,hub_hid_column_name_2

How can i do it in MySQL? Ideally without a procedure.

1 Answer 1

1

Here's a solution:

WITH RECURSIVE num AS (
  SELECT 1 AS n
  UNION
  SELECT n+1 FROM num WHERE n < 3 -- here is where you change your number
)
SELECT CONCAT('target_table,', 
  GROUP_CONCAT(CONCAT('hub_hid_column_',n-1,',hub_hid_column_name_',n-1))) AS list
FROM num;

Output:

+-----------------------------------------------------------------------------------------------------------------------------------+
| list                                                                                                                              |
+-----------------------------------------------------------------------------------------------------------------------------------+
| target_table,hub_hid_column_0,hub_hid_column_name_0,hub_hid_column_1,hub_hid_column_name_1,hub_hid_column_2,hub_hid_column_name_2 |
+-----------------------------------------------------------------------------------------------------------------------------------+

While SQL is great for certain tasks, other languages may be better suited to this task.

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

1 Comment

Awesome! Thank you!

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.