Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL split values to multiple rows

I have table :

id | name     1  | a,b,c     2  | b 

i want output like this :

id | name     1  | a     1  | b     1  | c     2  | b 
like image 824
AFD Avatar asked Jul 30 '13 08:07

AFD


People also ask

How do I split one row into multiple rows in SQL?

I used STRING_SPLIT() which is a table valued function supports SQL server 2016 and higher versions. You need to provide the formatted string into this function and use cross apply to join and generate the desired output.

How do I separate multiple values in SQL?

The Solution: Use STRING_SPLIT( ) DECLARE @categories VARCHAR(MAX) = 'value1,value2,value3'; Then you can use the STRING_SPLIT() function to turn those values into a recordset/array. Once it's in that format, you can use it in your IN clause as criteria.


1 Answers

If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this:

select   tablename.id,   SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name from   numbers inner join tablename   on CHAR_LENGTH(tablename.name)      -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1 order by   id, n 

Please see fiddle here.

If you cannot create a table, then a solution can be this:

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 union all select 5) numbers INNER JOIN tablename   on CHAR_LENGTH(tablename.name)      -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1 order by   id, n 

an example fiddle is here.

like image 174
fthiella Avatar answered Oct 09 '22 07:10

fthiella