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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With