Table:
id | name
1 | a,b,c
2 | b
Output
id | name
1 | a
1 | b
1 | c
2 | b
I found this query online and it works fine in mySql Phpmyadmin query editor.
SELECT
tablename.id, SUBSTRING_INDEX(SUBSTRING_INDEX (tablename.name, ',', numbers.n), ',', - 1) NAME
FROM (SELECT 1 n UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4) numbers
INNER JOIN tablename
ON CHAR_LENGTH (tablename.name) - CHAR_LENGTH (REPLACE (tablename.name, ',', '')) >= numbers.n - 1
ORDER BY id, n
But in SQL Server, it throws
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]'SUBSTRING_INDEX' is not a recognized built-in function name.
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'numbers'.
Edit: This query uses in tableau development, Where TSQL is not working as expecting
3
Answers
On SQL Server 2016 and later, we can use
STRING_SPLIT
here:Try this:
You could use a recursive CTE as the following
Online demo