I have a column that is returned by an SQL query.
Above is the column results, I need to separate the values in respect to a comma (,) to different columns.
I have a column that is returned by an SQL query.
Above is the column results, I need to separate the values in respect to a comma (,) to different columns.
Try This:
SELECT s.PET_NAME
FROM Table1 CROSS APPLY
STRING_SPLIT(PET_NAME, ',') s(PET_NAME);
For example via xml:
-- split to columns
select
ltrim(rtrim(t.x.value('(x)[1]', 'varchar(20)'))) as pet1,
ltrim(rtrim(t.x.value('(x)[2]', 'varchar(20)'))) as pet2,
ltrim(rtrim(t.x.value('(x)[3]', 'varchar(20)'))) as pet3,
ltrim(rtrim(t.x.value('(x)[4]', 'varchar(20)'))) as pet4,
ltrim(rtrim(t.x.value('(x)[5]', 'varchar(20)'))) as pet5
from (
select cast(('<x>'+replace(pet_name, ',','</x><x>')+'</x>') as xml) x
from YourTable) t (x)
You can use for example substring function, but it's more complicated because non-deterministic count of possible columns. For ad-hoc parsing is the best tool text editor, for example excel (ribbon Data/Text to columns).
For spliting into columns you cannot use STRING_SPLIT (it will split into rows).